尝试在try语句中追加时失败

2024-09-29 02:17:17 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个小程序,可以读取一个文件,如果它不存在,就创建它。 但是,当您尝试读取第二个和第三个文件的内容并将其附加到第一个文件时,它会失败。 我在代码中准确地标记了失败的地方

它总是跳转到例外部分,我没有把它包括在这里,因为它似乎不必要(例外部分)

with open ('lista1.txt','r') as file_1:
reader_0 = file_1.readlines() #reads a list of searchterms, the first search term of this list is "gt-710"

for search in reader_0:
    # creates the txt string component of the file to be created, this is the first one 
    file_0 = search.replace("\n","") +".txt" 
    file_1 = str(file_0.strip())
    
    # creates the txt string component of the file to be created, this is the second one
    files_2 = search.replace("\n","") +"2.txt" 
    file_2 = str(files_2.strip())
    
    # creates the txt string component of the file to be created, this is the second one
    files_3 = search.replace("\n","") +"3.txt" 
    file_3 = str(files_3.strip())
    
    try: #if the file named the same as the searchterm exists, read its contents    
        file = open(file_1,"r")
        file2 = open(file_2,"r")
        file3 = open(file_3,"r")

        file_contents = file.readlines()
        file_contents2 = file2.readlines()
        file_contents3 = file3.readlines()

        file = open(file_1,"a") #appends the contents of file 3 and file 2 to file 1

        print("im about here")

        file.write(file_contents2) #fails exactly here I don't know why
        file.write(file_contents3)

        file2 = open(file_2,"w+")
        file2.write(file_contents)

        file3 = open(file_3,"w+")
        file3.write(file_contents2)

Tags: ofthetotxtsearchiscontentsfiles
2条回答

使用file = open(file_1, 'r')file_开始读取,然后在追加模式下再次打开它,而不关闭第一个I/O操作-当在读取模式下打开查找时尝试写入时会导致失败

更改文件读/写以使用不易出错的with open语法,如下所示:

with open(file_1, 'r') as file_handle:
    file_contents = file_handle.read()

with open(file_2, 'r') as file_handle:
    file_contents2 = file_handle.read()

with open(file_3, 'r') as file_handle:
    file_contents3 = file_handle.read()

with open(file_1, 'a') as file_handle:
    file_handle.write(file_contents2)

# etc.

当文件不再打开时,以及在什么状态下打开时,这种语法非常明显

在您提到的地方失败的原因是您试图将列表写入文件(而不是字符串)file2.readlines()返回一个字符串列表,每个字符串都是它们自己的行,因此要修复此问题,请将所有readlines更改为filexxx.read(),将整个文件内容作为字符串返回

我还建议对其他答案状态进行更改,以使代码更具可读性/健壮性

相关问题 更多 >