如何在python的帮助下删除文件中的所有空行?

use*_*070 16 python

例如,我们有一些这样的文件:

第一行
第二行

第三行

结果我们必须得到:

第一行
第二行
第三行

仅使用python

gho*_*g74 26

import fileinput
for line in fileinput.FileInput("file",inplace=1):
    if line.rstrip():
        print line
Run Code Online (Sandbox Code Playgroud)

  • Markdown格式化使用尾随空格.删除对此答案的简单更改将使用空格删除行并保留尾随空格:`if line.rstrip():print line` (3认同)
  • +1 还可以捕获包含空格而没有其他内容的行。 (2认同)
  • 即使在好的行中,这也会改变空格的格式 (2认同)

Tho*_*hle 26

with语句非常适合自动打开和关闭文件.

with open('myfile','rw') as file:
    for line in file:
        if not line.isspace():
            file.write(line)
Run Code Online (Sandbox Code Playgroud)

  • Python 3:ValueError:必须恰好具有创建/读取/写入/追加模式之一。这个解决方案真的有效吗? (7认同)
  • +1使用"with"和良好的pythonic迭代通过线,除了不改变好的输出线. (5认同)
  • 看来你必须根据https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files用`r +`标志而不是`rw`打开myfile (2认同)
  • 对于任何大于输入缓冲区大小的文件,此解决方案似乎都会出现缓冲/覆盖问题.如果没有,有人可以解释原因吗? (2认同)

Joh*_*ooy 9

import sys
with open("file.txt") as f:
    for line in f:
        if not line.isspace():
            sys.stdout.write(line)
Run Code Online (Sandbox Code Playgroud)

另一种方式是

with open("file.txt") as f:
    print "".join(line for line in f if not line.isspace())
Run Code Online (Sandbox Code Playgroud)


小智 5

with open(fname, 'r+') as fd:
    lines = fd.readlines()
    fd.seek(0)
    fd.writelines(line for line in lines if line.strip())
    fd.truncate()
Run Code Online (Sandbox Code Playgroud)