我编写了一个程序来循环浏览一个文本文件文件夹,并逐个读取该文件并将其编辑内容写入新的txt文件。当我写一个新文件时,我在文件名中添加了“ JSP”,因此我添加了一个if语句,以避免使用名称为JSP的文件进行编辑。它给我一个错误消息,提示它尝试对JSP文件执行方法writeToFile,但在文件夹中找不到该方法。这让我感到困惑,因为
有什么想法吗?
import program
import os
def main():
directoryStr = "/Users/Elle/Documents/TMR/txtfiles/untitled folder"
directory = os.fsencode(directoryStr)
for file in os.listdir(directory):
filename = os.fsdecode(file)
if ".txt" in filename and "JSP" not in filename:
storeProcedure = program.StoreProcedure(filename)
storeProcedure.writeToFile()
main()
newFile = open(self.newName + ".txt", "w", encoding="utf16")
FileNotFoundError: [Errno 2] No such file or directory: 'JSP_Pgm_JpgmAPARCustSummary_Ctrl_Pay/Rec_summedbycustid_LtorGr0.txt'
答案 0 :(得分:1)
尝试以这种方式做事-正如我在评论中说的,os.listdir()
会为您提供文件名列表,而不是完整的文件路径。
import program
import os
def main():
directory = "/Users/Elle/Documents/TMR/txtfiles/untitled folder"
for filename in os.listdir(directory):
if ".txt" in filename and "JSP" not in filename:
filepath = os.path.join(directory, filename)
storeProcedure = program.StoreProcedure(filepath)
storeProcedure.writeToFile()
main()