Attempting to read open file a second time gets no data

前端 未结 4 1805
情话喂你
情话喂你 2020-12-02 00:47
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)
  fi         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 01:24

    Once you read a complete file into memory, reading some more from that file will result in an empty string being returned:

    >>> example = open('foobar.txt')
    >>> example.read()
    'Foo Bar\n'
    >>> example.read()
    ''
    

    In other words, you have reached the end of the file. You have three alternatives here:

    1. Re-open the file for each complete read.
    2. Use .seek() to go to the start of the file again:

      >>> example = open('foobar.txt')
      >>> example.read()
      'Foo Bar\n'
      >>> example.seek(0)
      >>> example.read()
      'Foo Bar\n'
      
    3. Store the contents of the file in a variable, thus caching it in memory, then use that instead of re-reading the file.

提交回复
热议问题