[英]Remove line breaks from txt file
如果我想从文本文件中删除换行符,例如:
hello
there
我使用这样一个简单的代码:
with open('words.txt') as text:
for line in text:
print (line.strip())
它输出这个:
hello
there
但是,我希望我的代码输出:
hello
there
我怎样才能做到这一点? 提前致谢。
if line.strip() == '': continue
在print
语句之前if line.strip() == '': continue
。
我看到两种方法来实现你想要的。
逐行阅读
with open('bla.txt') as stream: for line in stream: # Empty lines will be ignored if line.strip(): print(line)
阅读所有内容
import re with open('bla.txt') as stream: contents = stream.read() print re.sub('\\s$', '', contents, flags=re.MULTILINE)
如果你想删除它唯一的换行符,你可以使用string.replace("\\n", "")
或者如果它只使用carraige返回而不是换行符(* nix)那么string.replace("\\r", "")
詹姆士
您需要测试一行是否为空以解决此问题。
with open('words.txt') as text:
for line in text:
if line:
print (line.strip())
在python中,空字符串是假的。 也就是说,对空字符串的if-test将被视为false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.