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)
Your issue is that you open in write mode. To append to file you want to use append. See here.
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