首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,读取文件

Python,读取文件
EN

Stack Overflow用户
提问于 2020-06-29 18:41:40
回答 1查看 35关注 0票数 0

我正在研究如何在Python中使用文件(read()和readline()方法)。现在,我正在尝试使用这些方法访问具体的元素。我想知道使用方括号和圆括号访问有什么区别。我知道索引是使用方括号的,但是四舍五入呢?为什么结果看起来是这样?那么你推荐使用更多的方法是什么呢?谢谢你的帮助。

文件:

醒醒!因为“夜碗中的黎明”抛出了那块能让群星飞起来的石头:瞧!东方猎人在光的套索中抓住了苏丹的炮塔!

代码语言:javascript
复制
new = '/Users/tt/Desktop/omar.py'
poem = open(new, 'r')
lines = poem.read()
lines[0]
'A'
lines[1]
'w'
poem.close()


new = '/Users/tt/Desktop/omar.py'
poem = open(new, 'r')
poem.read(0)
''
poem.read(1)
'A'
poem.read(2)
'wa'
poem.read(3)
'ke!'
poem.close()

new = '/Users/tt/Desktop/omar.py'
poem = open(new, 'r')
poem.readlines(0)
['Awake! For Morning In the Bowl of Night\n', 'Has flung the Stone that puts the Stars to 
Flight:\n', 'And Lo! the Hunter of the East has caught\n', "The Sultan's Turret in a Noose of 
Light!\n"]
poem.readlines(1)
[]
poem.readlines(2)
[]
poem.close()

new = '/Users/tt/Desktop/omar.py'
poem = open(new, 'r')
poem.readlines(1)
['Awake! For Morning In the Bowl of Night\n']
poem.readlines(2)
['Has flung the Stone that puts the Stars to Flight:\n']
poem.close()


new = '/Users/tt/Desktop/omar.py'
poem = open(new, 'r')
lines = poem.readlines()
lines[0]
'Awake! For Morning In the Bowl of Night\n'
lines[1]
'Has flung the Stone that puts the Stars to Flight:\n'
poem.close()
EN

回答 1

Stack Overflow用户

发布于 2020-06-29 18:48:04

正如简要解释的here,如果提供整数作为read(n)的参数,则文件读取器仅读取文件的前n字符。

如果您首先read()所有内容,那么整个输入都存储在内存中。如果您随后通过执行以下操作访问read对象

代码语言:javascript
复制
lines = poem.read()
lines[0]

然后,您基本上只需从存储的序列中选取第一个元素,但您确实将整个序列存储在内存中。

因此,基本上,如果输入文件不是那么大,我建议在大多数情况下使用方括号语法,因为它可以消除访问字段时的一些混乱。但是,例如,如果您浏览了数千个文件,并且知道只需要第一行或前10个字符,那么一定要使用read(n)表示法。

希望这个直觉能帮上忙!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62636360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档