我想迭代每个文件,修剪每行的空格,如果返回的字符串为空则删除该行。有没有办法避免在下面的列表推导中重复.strip()调用?它不是性能关键,但感觉不对。
sub main():
fname = "foo.txt"
lns = []
with open(fname, 'r') as file:
lns = file.readlines()
newlns = [i.strip() + "\n" for i in lns if i.strip()]
#I want this to look like the following, which doesn't work:
#newlns = [y + "\n" for i in lns if i.strip() as y]
with open("out.txt", 'w') as file:
file.writelines(newlns)
答案 0 :(得分:4)
您可以使用嵌套列表推导(在这种情况下,生成器表达式以避免实际构建列表):
newlns = [i + "\n" for i in (line.strip() for ln in lns) if i]
实际上你真的不应该先费心去读取文件,只是把它放在那里:迭代文件会产生它的行。
with open(fname, 'r') as file:
newlns = [i + "\n" for i in (line.strip() for ln in file) if i]