【发布时间】: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?
【问题讨论】:
-
这些解决方案会发生什么?换行符还在吗?你只是打印输出,还是实际重写文件(我认为第一个链接只是
print(line),而不是重写文件 -
你有为此使用 Python 吗?使用
sed或grep之类的东西很容易做到这一点。 -
嗨@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