Python read()函数返回空字符串

Fra*_* R. 4 python file-io

如果我在Python中输入:

open("file","r").read()
Run Code Online (Sandbox Code Playgroud)

有时它会将文件的确切内容作为字符串返回,有时它会返回一个空字符串(即使文件不为空).有人可以解释一下这取决于什么?

pra*_*nsg 20

当您到达文件末尾(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.'
Run Code Online (Sandbox Code Playgroud)

文档链接: read() tell() seek()

注意:如果在您第一次读取文件时发生这种情况,请检查该文件是否为空.如果它没有尝试放在file.seek(0)之前read.

  • 我检查了我使用过的文件,它们都是空的。抱歉,是我的错 (2认同)

Mar*_*ers 6

file.read()方法文档:

立即遇到EOF时返回空字符串.

你已经命中了文件对象的末尾,没有更多的数据可供阅读.文件保持一个"当前位置",一个指向文件数据的指针,从0开始并在读取dada时递增.

请参阅file.tell()方法读出那个位置,和file.seek()方法去改变它.