尝试再次读取打开的文件不会获得任何数据

Ali*_*rld 3 python

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()
Run Code Online (Sandbox Code Playgroud)

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

Yuv*_*dam 7

文件对象应该被读取一次.一旦fin这样read(),你就再也无法从文件中读取任何其他内容了EOF.

要读取文件的内容,请调用f.read(size),它读取一些数据并将其作为字符串返回.size是可选的数字参数.当省略大小或为负时,将读取并返回文件的全部内容; 如果文件的大小是机器内存的两倍,那么这就是你的问题.否则,最多读取并返回大小字节.如果已到达文件末尾,f.read()将返回一个空字符串("").

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

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

def lst():
  fin.seek(0)
  return fin.readlines()
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 5

将完整文件读入内存后,从该文件中读取更多内容将导致返回空字符串:

>>> example = open('foobar.txt')
>>> example.read()
'Foo Bar\n'
>>> example.read()
''
Run Code Online (Sandbox Code Playgroud)

换句话说,您已到达文件末尾。您在这里有三种选择:

  1. 每次完整读取时重新打开文件。
  2. 使用.seek()再次转到文件的开头:

    >>> example = open('foobar.txt')
    >>> example.read()
    'Foo Bar\n'
    >>> example.seek(0)
    >>> example.read()
    'Foo Bar\n'
    
    Run Code Online (Sandbox Code Playgroud)
  3. 将文件的内容存储在变量中,从而将其缓存在内存中,然后使用它而不是重新读取文件。