【问题标题】:How to delete empty lines from a .txt file [duplicate]如何从 .t​​xt 文件中删除空行 [重复]
【发布时间】:2016-10-07 13:37:58
【问题描述】:

我有一个巨大的这种形式的输入 .txt 文件:

0 1 0 1 0 0 0 0 0 0

0 1 0 1 0 0 0 0 0 0

0 1 0 1 0 0 0 0 0 0

我想删除所有空行以创建一个新的输出 .txt 文件,如下所示:

0 1 0 1 0 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0

我尝试用 grep 来做:

grep -v '^$' test1.txt > test2.txt 

但我得到“SyntaxError: invalid syntax”

当我按照某人的建议使用 pandas 时,我得到不同数量的列,并且一些整数被转换为浮点数:例如:1.0 而不是 1

当我按照inspectorG4dget 的建议进行操作时(见下文),效果很好,只有一个问题:最后一行没有完全打印:

with open('path/to/file') as infile, open('output.txt', 'w') as outfile:
    for line in infile:
        if not line.strip(): continue  # skip the empty line
        outfile.write(line)  # non-empty line. Write it to output

那一定是我的文件有问题...

我已经在下面(和其他)处理过类似的帖子,但它们在我的情况下不起作用,主要是由于上面解释的原因

How to delete all blank lines in the file with the help of python?

one liner for removing blank lines from a file in python?

【问题讨论】:

  • 这些解决方案会发生什么?换行符还在吗?你只是打印输出,还是实际重写文件(我认为第一个链接只是print(line),而不是重写文件
  • 为此使用 Python 吗?使用 sedgrep 之类的东西很容易做到这一点。
  • 嗨@dwanderson,我想创建一个像输出一样的新文件。在某些情况下,换行符仍然存在,在其他情况下,它会以一种奇怪的方式打印出来,如下所示:0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0
  • python中是否有fgets的等价物?因为这会将行输入一个字符串,然后您可以使用长度函数来检查它是否等于 0。然后您可以在条件语句中做任何您想做的事情
  • @idjaw ,我知道用 grep 很容易做到这一点,但这将是一个大型 python 脚本的一部分,我想自动化它以对许多文件进行计算,所以它必须是 Python

标签: python


【解决方案1】:

你可以使用strip();

for line in yourTxtFile:
   if not line.strip():
      # write new file
      print (line)

【讨论】:

  • 这应该是if line.strip():。很抱歉评论一个 5 岁的答案:)
【解决方案2】:

我会这样做:

with open('path/to/file') as infile, open('output.txt', 'w') as outfile:
    for line in infile:
        if not line.strip(): continue  # skip the empty line
        outfile.write(line)  # non-empty line. Write it to output

【讨论】:

  • 谢谢@inspectorG4dget。正如我在编辑后的帖子中提到的,我尝试了你的方法,效果很好,唯一的问题是最后一行没有完全打印。在发布之前,我检查了您标记为“重复”的类似帖子,我遇到了同样的问题,这就是为什么我认为脚本有错误,但它可能是我的文件...
  • @Lucas:正如您在帖子中提到的,我认为这是您的文件的问题。你确定它没有任何奇怪的字符吗?也许尝试打印它(或输出ord 值)以找出答案?
猜你喜欢
  • 2016-05-29
  • 2022-07-02
  • 1970-01-01
  • 2012-06-03
  • 1970-01-01
  • 2014-03-17
  • 1970-01-01
  • 2021-08-19
  • 2021-12-27
相关资源
最近更新 更多