2013-02-26 163 views
1

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

回答

5

objStreamReader.ReadLinechops off the terminating newline,而Python的file.readlinekeeps it

如果您的文件在文本模式下打开(除非您明确指定,否则它是),行结束将始终为空(仅限最后一行)或只有一个\n,您可以安全地将其切断rstrip('\n')

0

第144个字符是换行符。

with open("file_path") as file: 
    for line in file: 
     line = line.rstrip("\n") # strip newline 
     print(len(line)) # should print 143