我有这段代码,它执行 sql SELECT 命令并在文本文件中返回结果。这工作得很好,但我在文本文件的末尾有一个空行,我需要删除它。
cursor.execute(sql_p11)
with open('D:\Automate\Output\out.txt', 'w') as myFile:
for row in cursor:
print(row[0], file=myFile)
这有两个部分:
end=''
到print()
peekable
第三方more_itertools
库来完成重写循环看起来像这样:
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='')
使用peekable
看起来像这样:
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 '')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句