【问题标题】:Read lines in Python keeping trailing whitespaces读取 Python 中的行,保留尾随空格
【发布时间】:2021-03-15 11:41:44
【问题描述】:

我需要读取每行都有一些尾随空格的文件。例如(本例中的 • 用于表示空格):

dog•••••••
black•cat•
bird••••••
horse••
pig•••••••

每一行,除了horse••,都有10个字符,所以我必须从文件中删除horse••

目前我正在使用以下代码:

  with open(file_path, "r+") as f:
    d = f.readlines()
    f.seek(0)
    for line in d:
      print(len(line))
      if len(line) == 11: # 10+1 (+1 is for the \n)
        f.write(line)
  f.truncate()
  return

然后打印出来:

4
10
5
6
4

如何在 Python 中读取文件时还包含尾随空格?

【问题讨论】:

  • 请确保您用于编辑文件的任何编辑器在保存时不会自动去除尾随空格。
  • 您的输出数据将始终具有与输入相同的长度,因此覆盖现有文件不是最好的主意,因为它可能会留下不必要的数据。打开另一个文件进行输出并(如果需要)替换现有的o_f.writelines(filter(lambda x: len(x.rstrip("\r\n")) == 10, f))

标签: python file whitespace readline


【解决方案1】:

正如rdas所提到的,PyCharm 正在从 txt 文件中删除尾随空格。

发布的代码完美运行。

【讨论】:

    【解决方案2】:

    也许可以试试

    with open(file_path, "r+") as f:
        d = f.readlines()
        f.seek(0)
        for line in d:
            print(len(line.split()))
            if len(line.split()) == 11:  # 10+1 (+1 is for the \n)
                f.write(line)
        f.truncate()
    

    【讨论】:

    • 你不需要分割线,len(line) 可以工作。 (+1 is for the \n) 也不会总是有效(\r\n 在 Windows 上是 +2
    猜你喜欢
    • 1970-01-01
    • 2012-12-10
    • 2014-08-13
    • 1970-01-01
    • 2014-01-13
    • 2022-12-03
    • 2015-05-30
    • 2012-10-22
    • 1970-01-01
    相关资源
    最近更新 更多