如何使用另一个脚本删除代码中的尾随空格?

kam*_*mal 58 python

就像是:

import fileinput

for lines in fileinput.FileInput("test.txt", inplace=1):
    lines = lines.strip()
    if lines == '': continue
    print lines
Run Code Online (Sandbox Code Playgroud)

但是在stdout上没有印刷任何东西.

假设一些字符串命名为foo:

foo.lstrip() # to remove leading white space
foo.rstrip() # to remove trailing whitespace
foo.strip()  # to remove both lead and trailing whitespace
Run Code Online (Sandbox Code Playgroud)

nmi*_*els 61

fileinput似乎是针对多个输入流.这就是我要做的:

with open("test.txt") as file:
    for line in file:
        line = line.rstrip()
        if line:
            print(line)
Run Code Online (Sandbox Code Playgroud)


mar*_*eau 10

您没有看到print语句的任何输出,因为在给出关键字参数时FileInput重定向stdout到输入文件inplace=1.这会导致输入文件被有效地重写,如果你看之后它中的行确实没有尾随或前导空格(除了print语句添加的每个末尾的换行符).

如果您只想删除尾随空格,则应使用rstrip()而不是strip().另外请注意,if lines == '': continue是造成空行被完全删除(无论是否strip还是rstrip被使用).

除非您的意图是重写输入文件,否则您应该只使用for line in open(filename):.否则,您可以通过sys.stderr使用以下内容同时回显输出来查看写入文件的内容:

import fileinput
import sys

for line in (line.rstrip() for line in
                fileinput.FileInput("test.txt", inplace=1)):
    if line:
        print line
        print >>sys.stderr, line
Run Code Online (Sandbox Code Playgroud)


Par*_*der 5

如果您正在寻找整理PEP8,这将修剪整个项目的尾随空白:

import os

PATH = '/path/to/your/project'

for path, dirs, files in os.walk(PATH):
    for f in files:
        file_name, file_extension = os.path.splitext(f)
        if file_extension == '.py':
            path_name = os.path.join(path, f)
            with open(path_name, 'r') as fh:
                new = [line.rstrip() for line in fh]
            with open(path_name, 'w') as fh:
                [fh.write('%s\n' % line) for line in new]
Run Code Online (Sandbox Code Playgroud)

  • Necro-comment:最后,不是浪费资源创建一个抛弃列表,而是使用带有生成器表达式的参数的单个文件输出调用更有效:即`fh.writelines((line +'\n'代表新行))`. (2认同)