Skip to main content
 首页 » 编程设计

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

2025年05月04日10www_RR

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(并在之后关闭)。正如所写,每次打开文件 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