Python read() 函数返回空字符串 [英] Python read() function returns empty string

查看:70
本文介绍了Python read() 函数返回空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 Python 中输入:

open("file","r").read()

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

解决方案

当你到达文件尾 (EOF) 时,.read 方法返回 '',因为没有更多的数据要读取.

<预><代码>>>>f = open('my_file.txt')>>>f.read() # 读取整个文件我的文件有数据.">>>f.read() # 到达文件末尾''>>>f.tell() # 给出我当前在文件中的位置17>>>f.seek(0) # 回到起始位置>>>f.read() # 并再次读取文件我的文件有数据."

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

<块引用>

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

If I type this in Python:

open("file","r").read()

sometimes it returns the exact content of the file as a string, some other times it returns an empty string (even if the file is not empty). Can someone explain what does this depend on?

解决方案

When you reach the end of file (EOF) , the .read method returns '', as there is no more data to 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.'

Doc links: read() tell() seek()

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 the read.

这篇关于Python read() 函数返回空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆