Why can i read lines from file only one time?

后端 未结 4 1586
旧时难觅i
旧时难觅i 2020-12-07 01:42

I have a file containing python\'s object as string, then i open it and doing things like i showing:

>>> file = open(\'gods.txt\')
>>> file         


        
4条回答
  •  情歌与酒
    2020-12-07 02:43

    Your position in the file has moved

    f = open("/home/usr/stuff", "r")
    f.tell()
    # shows you're at the start of the file
    l = f.readlines()
    f.tell()
    # now shows your file position is at the end of the file
    

    readlines() gives you a list of contents of the file, and you can read that list over and over. It's good practice to close the file after reading it, and then use the contents you've got from the file. Don't keep trying to read the file contents over and over, you've already got it.

提交回复
热议问题