Python:file.readline在行尾添加一个空格
我正在使用python读取一个空格填充的文本文件。文本文件验证的一部分是,文本文件中的每一行都应该是特定的文件长度,包括空格填充 当我使用下面的代码时,python最终给了我一行额外的空间。例如,我希望fileX中的所有行都有143个字符。Python会将其读取为144个字符,因此表示该文件无效。如果我在VB.NET中也这样做,我会得到正确的143个字符Python:file.readline在行尾添加一个空格,python,Python,我正在使用python读取一个空格填充的文本文件。文本文件验证的一部分是,文本文件中的每一行都应该是特定的文件长度,包括空格填充 当我使用下面的代码时,python最终给了我一行额外的空间。例如,我希望fileX中的所有行都有143个字符。Python会将其读取为144个字符,因此表示该文件无效。如果我在VB.NET中也这样做,我会得到正确的143个字符 Using objStreamReader As StreamReader = New StreamReader(myFilePath)
Using objStreamReader As StreamReader = New StreamReader(myFilePath)
While objStreamReader.EndOfStream = False
line = objStreamReader.ReadLine
len(line) 'This returns the correct length of 143.
为什么Python的readline函数会添加一个额外的字符?(使用python 3.2)
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将不是正确的机制,因为我可能会删除有用的空间。请记住,该文件的最大填充长度为给定的最大长度。
objStreamReader.ReadLine
,而Python的file.ReadLine
如果您的文件是以文本模式打开的(除非您明确指定,否则它是),则行尾将始终为空(仅最后一行)或正好是一个
\n
,并且您可以使用rstrip('\n')
objStreamReader.ReadLine
,,而Python的file.readline
如果您的文件是以文本模式打开的(除非您明确指定,否则它是),则行尾将始终为零(仅最后一行)或正好是一个
\n
,您可以使用rstrip('\n')
安全地将其切掉。第144个字符是换行字符
with open("file_path") as file:
for line in file:
line = line.rstrip("\n") # strip newline
print(len(line)) # should print 143
第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)
使用列表理解,您可以按以下方式执行此操作:
def readfile():
with open(filename, 'r') as fh:
lines = [line.rstrip('\n') for line in fh.readlines()]
for line in lines:
print (line)