V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2020-04-06 12:57:02 +08:00 · 2142 次点击
    这是一个创建于 1479 天前的主题,其中的信息可能已经有所发展或是发生改变。

    文档打开之后,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 条回复    2020-04-07 00:03:47 +08:00
    felix021
        1
    felix021  
       2020-04-06 12:59:45 +08:00   ❤️ 1
    f.readlines() 读取了文件的所有内容,这时候文件的读指针已经在末尾了。
    jmc891205
        2
    jmc891205  
       2020-04-06 13:51:14 +08:00   ❤️ 1
    因为你调用过 readlines 之后 the stream position 已经在文件末尾了
    所以你再调用 readlines 就读不到任何东西了


    要么你先用一个变量把 readlines 的返回值存一下
    要么你在第二次调用 readlines 之前调用一下 seek
    aloxaf
        3
    aloxaf  
       2020-04-06 22:58:53 +08:00
    题外话:这里直接 enumerate(f) 即可,.readlines() 多此一举(
    Kobayashi
        4
    Kobayashi  
       2020-04-07 00:03:47 +08:00 via Android
    f.seek(0)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3204 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 13:33 · PVG 21:33 · LAX 06:33 · JFK 09:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.