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

2018-12-06 16:47:32 +08:00
 eastlhu

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 新手,求大佬解惑

1212 次点击
所在节点    Python
3 条回复
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
2018-12-06 17:06:43 +08:00
@holajamc 你可以看看我的执行结果 ![]( https://i.loli.net/2018/12/06/5c08e64ebe35d.png)
eastlhu
2018-12-06 17:10:54 +08:00
@holajamc 我知道了,文件指针的问题,被移动到结尾了。谢谢。readlines 前 project_file.seek(0, 0)就好了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/515022

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX