[英]Python: file.readline adding a space at the end of the line
我正在使用python读取带有空格的纯文本文件。 验证文本文件的一部分是,希望文本文件中的每一行都是特定的文件长度,包括空格。
当我使用以下代码时,python最终给了我一行多余的空间。 例如,我希望fileX中的所有行都具有143个字符。 Python会将其读取为144个字符,因此表示该文件无效。 如果我在VB.NET中执行相同的操作,则会得到正确的143个字符。
为什么Python的 readline函数添加了额外的字符? (使用python 3.2)
import io
myfile = open("file_path", "r")
while True:
line = myfile.readline()
if not line:
break
print(len(line)) #This prints 144 characters
VB.NET提供了143个字符的正确长度。
Using objStreamReader As StreamReader = New StreamReader(myFilePath)
While objStreamReader.EndOfStream = False
line = objStreamReader.ReadLine
len(line) 'This returns the correct length of 143.
使用line.strip将不是正确的机制,因为我可能会舍弃有用的空间。 请记住,该文件使用空格填充,最大长度不能超过给定长度。
第144个字符是换行符。
with open("file_path") as file:
for line in file:
line = line.rstrip("\n") # strip newline
print(len(line)) # should print 143
使用列表推导,您可以执行以下操作:
def readfile():
with open(filename, 'r') as fh:
lines = [line.rstrip('\n') for line in fh.readlines()]
for line in lines:
print (line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.