推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
miniyao
V2EX  ›  Python

for index, line in enumerate(f.readlines()) 之后, f.readlines() 为什么会被清空了?

  •  
  •   miniyao · Apr 6, 2020 · 2888 views
    This topic created in 2363 days ago, the information mentioned may be changed or developed.

    文档打开之后,f = open('doc.txt', 'r') 通过 enumerate() 枚举,发现 f.readlines() 变成空列表 [] 啦?这是什么原因?

    f = open('doc.txt', 'r')
    for index, line in enumerate(f.readlines()):
        print(index, line)
        print(f.readlines())
    f.close()
    

    print(f.readlines()) 打印出来是空列表 []

    4 replies  •  2020-04-07 00:03:47 +08:00
    felix021
        1
    felix021  
       Apr 6, 2020   ❤️ 1
    f.readlines() 读取了文件的所有内容,这时候文件的读指针已经在末尾了。
    jmc891205
        2
    jmc891205  
       Apr 6, 2020   ❤️ 1
    因为你调用过 readlines 之后 the stream position 已经在文件末尾了
    所以你再调用 readlines 就读不到任何东西了


    要么你先用一个变量把 readlines 的返回值存一下
    要么你在第二次调用 readlines 之前调用一下 seek
    aloxaf
        3
    aloxaf  
       Apr 6, 2020
    题外话:这里直接 enumerate(f) 即可,.readlines() 多此一举(
    Kobayashi
        4
    Kobayashi  
       Apr 7, 2020 via Android
    f.seek(0)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   948 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 18:44 · PVG 02:44 · LAX 11:44 · JFK 14:44
    ♥ Do have faith in what you're doing.