a = open(“file”, “r”); a.readline() output without
我将要编写一个能够读取TXT文件的python脚本,但使用readline()时,始终会有输出。如何将其从变量中移除?
1 2 3 | a = open("file","r") b = a.readline() a.close() |
那就是:
1 2 | b.rstrip(' ') |
如果您想从每一行剥离空间,可以考虑:
1 | a.read().splitlines() |
这将为您提供一个没有行结束字符的行列表。
解决方案可以是:
1 2 | with open("file","r") as fd: lines = fd.read().splitlines() |
您将得到没有"
"或""的行列表。
或者,使用经典的方法:
1 2 3 | with open("file","r") as fd: for line in fd: line = line.strip() |
您逐行读取文件,并删除空格和换行符。
如果只想删除换行符:
1 2 3 4 5 | with open("file","r") as fd: for line in fd: line = line.replace(" ","").replace(" ","") |
ET Voice。
注意:python 3的行为有点不同。要模拟此行为,请使用
请参阅io.open的文档。
因此,您可以使用:
1 2 3 4 | with io.open("file","r", newline=None) as fd: for line in fd: line = line.replace(" ","") |
当newline参数为
'或'
'结尾,这些行被转换为''。
newline controls how universal newlines works (it only applies to text mode). It can be None, '', '
', '
', and ''. It works as follows:
On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '
', '
', or '', and these are translated into '
' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.