我正在使用 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 将不是正确的机制,因为我可能会摆脱有用的空间。请记住,文件被空格填充到最大给定长度。