Python - 删除文件末尾的空白文本行

标签 python python-3.x

我正在编写一个修改任何文本文件的脚本。它用空白行替换空白行。它删除文件末尾的空白行。该图像显示了我想要的输出。

enter image description here

我能够非常接近所需的输出。问题是我无法摆脱最后一个空行。我认为这与最后一行有关。例如 ' the lines below me should be gone 实际上看起来像这样 ' the lines below me should be gone\n' 看起来新行是在上一行创建的。例如,如果第 4 行有 \n,那么第 5 行实际上是空行而不是第 4 行。

我应该注意,我不能使用 rstripstrip

到目前为止我的代码。

def clean_file(filename):
    # function to check if the line can be deleted
    def is_all_whitespace(line):
        for char in line:
            if char != ' ' and char != '\n':
                return False
        return True

    # generates the new lines
    with open(filename, 'r') as file:
        file_out = []
        for line in file:
            if is_all_whitespace(line):
                line = '\n'
            file_out.append(line)

    # removes whitespaces at the end of file
    while file_out[-1] == '\n':  # while the last item in lst is blank
        file_out.pop(-1)  # removes last element

    # writes the new the output to file
    with open(filename, 'w') as file:
        file.write(''.join(file_out))

clean_file('test.txt')

最佳答案

\n 本质上意味着“创建另一行”

所以当你删除了所有 \n 的行时,前面的行仍然存在

the lines below me should be gone\n

这又意味着“创建另一行”,超出您已经删除的行

既然你说你不能使用rstrip,你可以结束循环

file_out[-1] = file_out[-1].strip('\n')

从最后一个元素中删除 \n。因为 \n 不能存在于一行中的任何其他位置,所以 rstripstrip 将具有相同的效果

或者没有任何 stripendswith:

if file_out[-1][-1] == '\n':
    file_out[-1] = file_out[-1][:-1]

注意\n是单个字符,序号0x0a为十六进制,不是两个字符\n,序数 0x5c0x6e。这就是我们使用 -1 而不是 -2

的原因

关于Python - 删除文件末尾的空白文本行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21446153/

相关文章:

python - 如何使用线条和标记绘制重叠系列?

python - tensorflow 中的 classifier.predict 错误(shape_and_slice 规范中的形状不匹配)

python - 如何只显示最后六个单词

python - 我的代码未按 python 3 中的 try 和 except 函数的预期运行

Python:用元组值更新字典键

python - VS代码中的文件夹

python - Sympy 集成没有给出正确答案

python - 从 Python 读取 FoxPro DBF 文件的最简单方法是什么?

python-3.x - 使用 sqlalchemy 和 Oracle 时 db.session.commit() 出错

python-3.x - 给定两个音频文件,其中一个是另一个的摘要,是否有一种python方法来查找何时在原始文件中重播该摘要?