从文本文件 PYTHON 中删除最后一个空行

玛丽亚姆·迈赫迪

我有这段代码,它执行 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)
吉日·鲍姆

这有两个部分:

重写循环看起来像这样:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章