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的数据。任何提示如何解决它?
答案 0 :(得分:8)
您可能希望在 for for循环之前打开output.txt
(之后再close
)。在编写时,每次打开文件时都会覆盖文件output.txt
。 (另一种选择是开放追加:output = open('output.txt','a')
,但这绝对不是在这里做到的最佳方式......
当然,现在最好使用上下文管理器(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
答案 1 :(得分:2)
您的问题是您以写入模式打开。要附加到文件,您要使用追加。请参阅here。