问题描述
因此,我有一个小程序读取文件并在不存在的情况下创建文件。 但是,当您尝试读取第二个和第三个文件的内容并将其附加到第一个文件时,它会失败。 我在代码中准确地标出了失败的地方。
它总是跳到例外部分,我没有在这里包括它,因为它似乎是不必要的(例外部分)
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)
解决方法
在您提到的那一刻失败的原因是您试图将列表写入文件(而不是字符串)。 file2.readlines()
返回一个字符串列表,每个字符串都是它们自己的行,因此为了解决此问题,将所有readlines
更改为filexxx.read()
,这会将整个文件内容作为字符串返回。
我还建议将更改更改为其他答案状态,以使您的代码更具可读性/鲁棒性。
,您开始使用file_
从file = open(file_1,'r')
进行读取,然后在追加模式下再次打开它,而没有关闭第一个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.
当不再打开文件以及打开文件处于什么状态时,这种语法非常明显。