Attempting to read open file a second time gets no data

前端 未结 4 1807
情话喂你
情话喂你 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:39

    Once you've called read() once fin has been read.

    If you want to read() it again (having discarded the contents on the first attempt), you'll need to re-open() or seek() the start of the file.

    I suggest you do this in lst(), or, better still, store the contents returned by lst()

    Aside from that...

    fin.write(str(len(lst()) + in)
    

    It's not clear what you're trying to do here, but you'd be better off using a stored return value from lst() and not using in as a variable name, since it's a reserved keyword.

    Something like:

    lines = lst()
    # [...]
    number_of_lines = len(lines)
    fin.write(str(number_of_lines) + some_other_str)
    

提交回复
热议问题