尝试第二次读取打开的文件没有数据 [英] Attempting to read open file a second time gets no data

查看:44
本文介绍了尝试第二次读取打开的文件没有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fin = open('/abc/xyz/test.txt', 'a+')

def lst():
  return fin.read().splitlines()

print lst()

def foo(in):
  print lst()
  fin.write(str(len(lst()) + in)
  fin.flush()

在上面的代码中,当 print lst() 在函数外被调用时,它给出了正确的结果,但是当试图在函数 foo() 中调用相同的函数时,它产生空列表这使得 len(lst()) 值为 0.我也尝试通过注释最后两行,但它仍然返回空列表.上面的代码有什么问题?

In above code when print lst() is called outside function it gives correct result, but when trying to call same function in function foo() it produces empty list which makes len(lst()) value 0. I also tried by commenting last two line but still it gives back empty list. What is wrong in above code?

推荐答案

文件对象应该被读取一次.一旦 fin 成为 read(),您就不能再从文件中读取任何其他内容,因为它已经达到了 EOF.

File objects are meant to be read once. Once fin has been read(), you can no longer read anything else from the file since it has already reached EOF.

要读取文件的内容,调用 f.read(size),它读取一些数据量并将其作为字符串返回.尺寸是可选的数字参数.当 size 被省略或为负时,整个文件内容将被读取并返回;这是你的问题,如果该文件是您机器内存的两倍大.否则,在大多数大小字节被读取并返回.如果文件的结尾已经到达时,f.read() 将返回一个空字符串 ("").

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects

如果您确实需要重入访问您的文件,请使用:

If you really need reentrant access to your file use:

def lst():
  fin.seek(0)
  return fin.readlines()

这篇关于尝试第二次读取打开的文件没有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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