Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python printing a blank line on the first line when writing to a file

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!

like image 700
Lance Collins Avatar asked Oct 23 '25 09:10

Lance Collins


1 Answers

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.

like image 157
Rafe Kettler Avatar answered Oct 25 '25 01:10

Rafe Kettler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!