我正在解析一个大文本文件,如果我只能以某种方式读取没有 '\n' 符号的行,我的生活会容易得多。例如:
Hello
World
由 python 的readLines()
as返回{'Hello\n','World\n'}
,而我需要获取{'Hello','World'}
. 有没有办法只读取打印的字符?
我知道可以使用正则表达式来完成,但我希望有一种更简单的方法来做到这一点。
谢谢!
您可以使用该rstrip()
功能来消除尾随换行符。对于您的具体示例:
In [9]: s = {'Hello\n','World\n'}
In [10]: s
Out[10]: set(['World\n', 'Hello\n'])
In [12]: for i in s:
....: print i
World
Hello
In [13]: for i in s:
....: print i.rstrip()
World
Hello
更多信息在这里:http ://docs.python.org/library/string.html
您可能会考虑在阅读文件时去掉换行符:
with open('data.txt') as infp:
for line in infp:
line = line.rstrip()
# rest of processing
with open('test_file.txt') as f:
my_list = [line.rstrip() for line in f]
如果您不想存储数据,而只想打印(或做任何您想做的事情)结果,您可以执行以下操作:
with open('test_file.txt') as f:
for line in f:
print line.rstrip() #or do whatever you want to
您也可以使用切片删除换行符:
s = "Hello\n"
print s[:-1]
"Hello"