I’m trying to write an output list to a file, but only getting the last line from the list to actually write to the file. How can I change my code so that it captures everything?
import os
slices = [(0,3), (12,28), (29,31), (32,33), (34,38), (130,144), (39,41), (32,33), (42,55), (58,64), (65,72), (73,74), (75,78), (79,84), (99,102)]
File = r"E:\file.txt"
outfile = r"E:\file_output.txt"
with open(File) as sourcefile:
for line in sourcefile:
result = [line[slice(*slc)] for slc in slices]
myfile = open(outfile, 'w')
for lines in result:
myfile.write("%s\t" % lines)
myfile.close()
Your for loop is re-assigning
resulteach iteration. Therefore, at the end of the loopresultstill only has one list in it. Assignmyfilebefore the loop, and put themyfile.writestatement inside the loop.Alternatively, if you want to have a list of all the results, you can use
+=to get a list of lists, as in