我正在使用python读取平坦的空格填充文本文件。文本文件验证的一部分是文本文件中的每一行都应该是包含空格填充的特定文件长度。Python:file.readline在行尾添加一个空格
当我使用下面的代码时,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不会是正确的机制,因为我可能会摆脱有用的空间。请记住,文件空间填充达到最大给定长度。