python printing a blank line on the first line when writing to a file
17,104
My guess is that the first file in zf.namelist()
doesn't contain anything, so you skip the for line in words
loop for that file and just do new_file.write('\n')
. It's difficult to tell without seeing the files that you're looping over; perhaps add some debug statements that print out the files' names and some info, e.g. their size.
Comments
-
Lance Collins almost 2 years
I'm stuck on why my code is printing a blank line before writing text to a file. What I am doing is reading two files from a zipped folder and writing the text to a new text file. I am getting the expected results in the file, except for the fact that there is a blank line on the first line of the file.
def test(): if zipfile.is_zipfile(r'C:\Users\test\Desktop\Zip_file.zip'): zf = zipfile.ZipFile(r'C:\Users\test\Desktop\Zip_file.zip') for filename in zf.namelist(): with zf.open(filename, 'r') as f: words = io.TextIOWrapper(f) new_file = io.open(r'C:\Users\test\Desktop\new_file.txt', 'a') for line in words: new_file.write(line) new_file.write('\n') else: pass zf.close() words.close() f.close() new_file.close()
Output in new_file (there is a blank line before the first "This is a test line...")
This is a test line... This is a test line... this is test #2 this is test #2
Any ideas?
Thanks!