gpt4 book ai didi

python - Python:file.readline在行尾添加一个空格

转载 作者:太空宇宙 更新时间:2023-11-04 09:11:07 27 4
gpt4 key购买 nike

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

最佳答案

objStreamReader.ReadLine chops off the terminating newline,而Python的file.readline keeps it

如果您的文件是在文本模式下打开的(除非您另外明确指定,否则),行尾将始终为空(仅最后一行)或恰好是一个\n,并且您可以使用

关于python - Python:file.readline在行尾添加一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15079800/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com