为什么循环覆盖我的文件,而不是写在文本之后?

i = 1 # keep track of file number directory = '/some/directory/' for i in range(1, 5170): #number of files in directory filename = directory + 'D' + str(i) + '.txt' input = open(filename) output = open('output.txt', 'w') input.readline() #ignore first line for g in range(0, 7): #write next seven lines to output.txt output.write(input.readline()) output.write('\n') #add newline to avoid mess output.close() input.close() i = i + 1 

我有这个代码,我试图得到一个文件,并将其重写到output.txt,但是当我想附加下一个文件,我的代码覆盖已附加的旧文件。 在代码完成的结果我有这样的事情:

 dataA[5169]=26 dataB[5169]=0 dataC[5169]=y dataD[5169]='something' dataE[5169]=x data_date[5169]=2012.06.02 

而不是数据范围从文件0到5169.任何提示如何解决它?

你的问题是,你打开写模式。 追加到文件,你想使用追加。 看到这里 。

您可能希望 for循环之前打开output.txt (并close它)。 按照写法,每次打开文件时都会覆盖文件output.txt 。 (另一种方法是打开追加: output = open('output.txt','a') ,但这绝对不是在这里做最好的方法…

当然,现在最好使用上下文pipe理器( with语句):

 i = 1 # keep track of file number <-- This line is useless in the code you posted directory = '/some/directory/' #<-- os.path.join is better for this stuff. with open('output.txt','w') as output: for i in range(1, 5170): #number of files in directory filename = directory + 'D' + str(i) + '.txt' with open(filename) as input: input.readline() #ignore first line for g in range(0, 7): #write next seven lines to output.txt output.write(input.readline()) output.write('\n') #add newline to avoid mess i = i + 1 #<---also useless line in the code you posted