我正在研究如何在Python中使用文件(read()和readline()方法)。现在,我正在尝试使用这些方法访问具体的元素。我想知道使用方括号和圆括号访问有什么区别。我知道索引是使用方括号的,但是四舍五入呢?为什么结果看起来是这样?那么你推荐使用更多的方法是什么呢?谢谢你的帮助。
文件:
醒醒!因为“夜碗中的黎明”抛出了那块能让群星飞起来的石头:瞧!东方猎人在光的套索中抓住了苏丹的炮塔!
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()发布于 2020-06-29 18:48:04
正如简要解释的here,如果提供整数作为read(n)的参数,则文件读取器仅读取文件的前n字符。
如果您首先read()所有内容,那么整个输入都存储在内存中。如果您随后通过执行以下操作访问read对象
lines = poem.read()
lines[0]然后,您基本上只需从存储的序列中选取第一个元素,但您确实将整个序列存储在内存中。
因此,基本上,如果输入文件不是那么大,我建议在大多数情况下使用方括号语法,因为它可以消除访问字段时的一些混乱。但是,例如,如果您浏览了数千个文件,并且知道只需要第一行或前10个字符,那么一定要使用read(n)表示法。
希望这个直觉能帮上忙!
https://stackoverflow.com/questions/62636360
复制相似问题