1
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 的数据。任何提示如何修复它?

4

2 回答 2

8

您可能希望在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
于 2012-10-25T13:20:49.437 回答
2

您的问题是您以写入模式打开。要附加到您要使用附加的文件。见这里

于 2012-10-25T13:22:20.637 回答