<分区>
如果我在 Python 中输入:
open("file","r").read()
有时它以字符串的形式返回文件的确切内容,有时它返回一个空字符串(即使文件不为空)。 谁能解释一下这取决于什么?
<分区>
如果我在 Python 中输入:
open("file","r").read()
有时它以字符串的形式返回文件的确切内容,有时它返回一个空字符串(即使文件不为空)。 谁能解释一下这取决于什么?
最佳答案
当您到达文件末尾 (EOF) 时,.read
方法返回 ''
,因为没有更多数据要读取。
>>> f = open('my_file.txt')
>>> f.read() # you read the entire file
'My File has data.'
>>> f.read() # you've reached the end of the file
''
>>> f.tell() # give my current position at file
17
>>> f.seek(0) # Go back to the starting position
>>> f.read() # and read the file again
'My File has data.'
Note: If this happens at the first time you read the file, check that the file is not empty. If it's not try putting
file.seek(0)
before theread
.
关于Python read() 函数返回空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374425/