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
eastlhu
V2EX  ›  Python

Python3:readlines 或者 enumerate 是否会导致文件流为空

  •  
  •   eastlhu · 2018-12-06 16:47:32 +08:00 · 1197 次点击
    这是一个创建于 1939 天前的主题,其中的信息可能已经有所发展或是发生改变。

    python3 环境 代码如下:

    file_path = os.getcwd() + "/test.txt"
    project_file = open(file_path,"r")
    #list_file = project_file.readlines()
    for index, line in enumerate(project_file):
        print("index=%d,linex=%s"%(index,line))
    

    test.txt 里面有一些任意文本内容,在注释掉第三行的情况下,下面的 print 能正常打印文本内容。 去除第三行的注释后,下面的 print 无打印,也就是 project_file 为空了? 同样的把 for 循环放到 readlines 上面,第一个 print 能正常打印文本内容,但是也会导致 list_file 为空,print 打出的长度为 0,代码如下:

    file_path = os.getcwd() + "/test.txt"
    project_file = open(file_path,"r")
    for index, line in enumerate(project_file):
        print("index=%d,linex=%s"%(index,line))
    list_file = project_file.readlines()
    print(len(list_file))
    

    我的问题是:enumerate 或者 readlines 操作过一次文件流后,是否会导致文件流为空?或者是我的使用有问题,我是 python 新手,求大佬解惑

    3 条回复    2018-12-06 17:10:54 +08:00
    holajamc
        1
    holajamc  
       2018-12-06 16:54:12 +08:00
    事实上是不会的
    In [1]: with open(file='README.md', mode='r', encoding='utf8') as f:
    ...: res = f.readlines()
    ...:

    In [2]: res
    Out[2]: ['这次会有比较多的代码,但核心代码都是你已经亲自写过的~\n', '请注意阅读顺序,ext 会作为课外阅读内容~']

    In [3]: for index, value in enumerate(res):
    ...: print(index, value)
    ...:
    0 这次会有比较多的代码,但核心代码都是你已经亲自写过的~

    1 请注意阅读顺序,ext 会作为课外阅读内容~
    eastlhu
        2
    eastlhu  
    OP
       2018-12-06 17:06:43 +08:00
    @holajamc 你可以看看我的执行结果 ![]( https://i.loli.net/2018/12/06/5c08e64ebe35d.png)
    eastlhu
        3
    eastlhu  
    OP
       2018-12-06 17:10:54 +08:00
    @holajamc 我知道了,文件指针的问题,被移动到结尾了。谢谢。readlines 前 project_file.seek(0, 0)就好了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4743 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 01:09 · PVG 09:09 · LAX 18:09 · JFK 21:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.