Python f.read() 在首次使用后发生变化
Python f.read() changing after first use
当我在 python 中打开一个文本文件来阅读它时,我第一次调用 f.read()
它工作正常但任何后续调用它 returns 一个空字符串(''
).即使在一行中再次使用它也会将其更改为空白字符串。
我正在阅读的文本是 0 到 128 之间的 unicode 字符的随机集合,如果有帮助的话。
例如:
>>> f = open("Data.txt")
>>> f.read()
'$$$\x00\x00\x11$$$'
>>> f.read()
''
>>> f.close()
这是什么原因造成的,我该如何解决?
这实际上是预期的行为并记录在 the official documentation:
...
If the end of the file has been
reached, f.read() will return an empty string ("").
它明确给出了与你相同的例子:
>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
您可以通过调用 seek()
:
重置文件指针
file.seek(0)
因此,在您的情况下,它将是:
>>> f = open("Data.txt")
>>> f.read()
'$$$\x00\x00\x11$$$'
>>> f.read()
''
>>> f.seek(0) # move the pointer to the beginning of the file again
>>> f.read()
'$$$\x00\x00\x11$$$'
>>> f.close()
当我在 python 中打开一个文本文件来阅读它时,我第一次调用 f.read()
它工作正常但任何后续调用它 returns 一个空字符串(''
).即使在一行中再次使用它也会将其更改为空白字符串。
我正在阅读的文本是 0 到 128 之间的 unicode 字符的随机集合,如果有帮助的话。
例如:
>>> f = open("Data.txt")
>>> f.read()
'$$$\x00\x00\x11$$$'
>>> f.read()
''
>>> f.close()
这是什么原因造成的,我该如何解决?
这实际上是预期的行为并记录在 the official documentation:
...
If the end of the file has been reached, f.read() will return an empty string ("").
它明确给出了与你相同的例子:
>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
您可以通过调用 seek()
:
file.seek(0)
因此,在您的情况下,它将是:
>>> f = open("Data.txt")
>>> f.read()
'$$$\x00\x00\x11$$$'
>>> f.read()
''
>>> f.seek(0) # move the pointer to the beginning of the file again
>>> f.read()
'$$$\x00\x00\x11$$$'
>>> f.close()