【问题标题】:Python - delete blank lines of text at the end of the filePython - 删除文件末尾的空白行
【发布时间】:2014-01-30 01:21:11
【问题描述】:

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

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

【问题讨论】:

  • 你对这个问题做了很多研究,很清楚。 +1。
  • 为什么“不能”使用.rstrip()
  • @KarlKnechtel 那太容易了
  • 这是家庭作业吗?

标签: python python-3.x


【解决方案1】:

\n 本质上的意思是“创建另一行”

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

the lines below me should be gone\n

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

既然你说你不能使用rstrip,你可以用

结束循环
file_out[-1] = file_out[-1].strip('\n')

从最后一个元素中删除\n。因为\n不能存在于一行的其他任何地方,所以rstripstrip会有同样的效果

或者没有any strip or endswith:

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

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

【讨论】:

  • @Vader 然后我怀疑你可以使用file_out[-1][-1] == '\n'
  • @Vader 为什么你认为使用-2'\n' 是一个字符。
  • @Vader '\n'一个 表示“换行符”的字符。反斜杠 ('\') 是一个转义符,用于将其与常规 'n' 区分开来。
  • @Vader 这样它就不会被解析器混淆为常规的'n'。转义后,解析器会将您看到的 '\n' 读取为单个字符,即“换行符”字符,而不是斜杠和“n”。
  • @Vader 对。另一个例子是空字符。 '\0'不是两个斜杠和零字符,而是一个整数字节0(也不是字符零)。