Home > Back-end >  Remove last blank line from text file PYTHON
Remove last blank line from text file PYTHON

Time:10-01

I have this code which executes an sql SELECT command and returns the result in a text file. This is working absolutely fine but I'm getting a blank line at the end of my text file which I need to remove.

cursor.execute(sql_p11)
with open('D:\Automate\Output\out.txt', 'w') as myFile:
    for row in cursor:
        print(row[0], file=myFile)

CodePudding user response:

There are two parts to this:

Rewriting the loop would look like this:

cursor.execute(sql_p11)
with open('D:\Automate\Output\out.txt', 'w') as myFile:
    for i, row in enumerate(cursor):
        if i > 0:
            print(file=myFile)
        print(row[0], file=myFile, end='')

Using peekable would look like this:

from more_itertools import peekable

cursor.execute(sql_p11)
with open('D:\Automate\Output\out.txt', 'w') as myFile:
    rows = peekable(cursor)
    for row in rows:
        print(row[0], file=myFile, end='\n' if rows else '')

CodePudding user response:

I'd propose to use myFile.write() instead of print(file=myFile)

cursor.execute(sql_p11)

with open('D:\Automate\Output\out.txt', 'w') as myFile:
    rows = [row[0] for row in cursor]
    myFile.write('\n'.join(rows))
  • Related