【问题标题】:Remove last blank line from text file PYTHON从文本文件 PYTHON 中删除最后一个空行
【发布时间】:2021-11-22 01:19:12
【问题描述】:

我有这段代码执行 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)

【问题讨论】:

  • 文本文件通常以换行符结尾。为什么需要删除它?
  • 我运行一个实用程序来进一步执行该文本文件。我的实用程序在找到除数字以外的空行时会出错。
  • 它们是不同的约定;在 Linux 上它们普遍存在,但在其他系统上不一定是这样
  • 当前输出:1 2 3 --空白行--所需输出:1 2 3

标签: python sql python-3.x


【解决方案1】:

这有两个部分:

重写循环如下所示:

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 '')

【讨论】:

  • 我尝试用你的代码重写循环,它删除了最后一个空白行,但现在我的输出文件看起来像这样:12345678 相反,我希望我的输出文件格式如下:1 2 3 4 5 6
  • 啊,我忘了把文件传给print();现在修复了。请再试一次好吗?
【解决方案2】:

我建议使用myFile.write() 而不是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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多