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:
- Omitting the newline itself is done by passing
end=''
toprint()
- Figuring out that you're on the last row of the cursor, which can be done either (a) by rewriting the loop, or (b) by using
peekable
from the third-partymore_itertools
library
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))