Python doesn't write every line to output file
I am trying to format/clean some data from a text file using Python. The columns are separated by tabs, and I only want certain columns from each row. I am running into a problem that is not making any sense to me and would appreciate some help. I am opening a file and then running a loop to take in every line from that file. I want to eventually do some formatting with each row before writing it to the output file, but I cannot even get every row from the input file to the output file, so this is the first step. Here is what I have:
rfile = open(input file path here, 'r') wfile = open(output file path here,'w') counter = 0 for line in rfile: x = line.split('\t') print(x) wfile.write(str(x) + '\n') counter +=1 print(counter)
The file has 9101 rows. When I look at the console after execution, there are 9101 printed rows. The counter variable, when printed, is 9101. When I go to my output file, there are only 9035 rows, not the 9101 that should be there. The output file looks exactly like the console (which is what it should look like), except it just stops at row 9035 for some unknown reason. I do not see any hidden characters or any spacing issues causing the problem and can’t find a solution anywhere else. Has anyone ran into this problem before or would someone need to see my text file? Thanks!
Answered, easy fix. Thanks for the help! Just needed to close the file so that the last buffer full of data could be written to the disk, as jasonharper pointed out. So add this at the end of the code snippet:
wfile.close() rfile.close()