栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python readlines不返回任何东西?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python readlines不返回任何东西?

你读的文件 已经 和文件指针不是在 末尾 的文件。

readlines()
然后调用将不会返回数据。

仅读取一次文件:

with open('current.cfg', 'r') as current:    lines = current.readlines()    if not lines:        print('FILE IS EMPTY')    else:        for line in lines: print(line)

另一种选择是在重新阅读之前先回到开头:

with open('current.cfg', 'r') as current:    if len(current.read()) == 0:        print('FILE IS EMPTY')    else:        current.seek(0)        for line in current.readlines(): print(line)

但这只是浪费CPU和I / O时间。

最好的办法是尝试和阅读
数据量,或寻求到了最后,通过采取文件的大小

file.tell()
,然后再寻找回到起点,一切不读。然后将文件用作迭代器,以防止将所有数据读取到内存中。这样,当文件很大时,您就不会产生内存问题:

with open('current.cfg', 'r') as current:    if len(current.read(1)) == 0:        print('FILE IS EMPTY')    else:        current.seek(0)        for line in current: print(line)

要么

with open('current.cfg', 'r') as current:    current.seek(0, 2)  # from the end    if current.tell() == 0:        print('FILE IS EMPTY')    else:        current.seek(0)        for line in current: print(line)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/652039.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号