繁体   English   中英

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

[英]Python - delete blank lines of text at the end of the file

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

在此输入图像描述

我能够非常接近所需的输出。 问题是我无法摆脱最后的空白行。 我认为这与最后一行有关。 例如' 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM