Why loop overwriting my file instead of writing after text?

前端 未结 2 1870
星月不相逢
星月不相逢 2021-01-16 01:40
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)         


        
相关标签:
2条回答
  • 2021-01-16 02:26

    Your issue is that you open in write mode. To append to file you want to use append. See here.

    0 讨论(0)
  • 2021-01-16 02:30

    You probably want to open output.txt before your for loop (and close it after). As it is written, you overwrite the file output.txt everytime you open it. (an alternative would be to open for appending: output = open('output.txt','a'), but that's definitely not the best way to do it here ...

    Of course, these days it's better to use a context manager (with statement):

    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
    
    0 讨论(0)
提交回复
热议问题