我有一个巨大的输入.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
Run Code Online (Sandbox Code Playgroud)
我想删除所有空行,以便创建一个新的输出.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
Run Code Online (Sandbox Code Playgroud)
我尝试用grep做:
grep -v '^$' test1.txt > test2.txt
Run Code Online (Sandbox Code Playgroud)
但我得到"SyntaxError:无效的语法"
当我按照某人的建议使用pandas时,我得到不同数量的列,并且一些整数被转换为浮点数:例如:1.0而不是1
当我按照督察G4dget的建议(见下文)时,它工作得很好,只有一个问题:最后一行没有完全打印:
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
Run Code Online (Sandbox Code Playgroud)
它必须是我的文件然后...
我已经在下面(以及其他人)处理了类似的帖子,但它们在我的情况下不起作用,主要是由于上面解释的原因
ins*_*get 11
我就是这样做的:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20215 次 |
| 最近记录: |