就像是:
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)
如果您正在寻找整理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)
归档时间: |
|
查看次数: |
111159 次 |
最近记录: |