Python的文件的read()和readline()柜台?

Kapish L:

它看起来像蟒蛇跟踪的read()和readline每次运行的()。这是增量,通过覆盖运行,并在年底,它不返回任何值。如何找到这个计数器,随时读取特定行?

编辑:我的目标是读几GB的大文件的大小,几十万行。如果一个迭代,然后是不够的,我不想加载整个文件在内存中。如何跳转到指定的行,而不必阅读不必要的行?

只有3行的文本文件。

# cat sample.txt
This is a sample text file. This is line 1
This is line 2
This is line 3

# python
Python 3.7.5 (default, Nov  7 2019, 10:50:52)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('sample.txt', 'r')
>>> file.readline()
'This is a sample text file. This is line 1\n'
>>> file.readline()
'This is line 2\n'
>>> file.readline()
'This is line 3\n'
>>> file.readline()
''
>>> file.readline()
''
>>> file.read()
''
>>> file.read(0)
''
>>> file.read()
''
>>>

# python
Python 3.7.5 (default, Nov  7 2019, 10:50:52)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('sample.txt', 'r')
>>> file.read()
'This is a sample text file. This is line 1\nThis is line 2\nThis is line 3\n'
>>> file.read()
''
>>> file.readline()
''
>>>
tobias_k:

Python中的文件对象是一个迭代,遍历该文件中的不同的行。您可以使用readlines()一次读取所有(剩余)行到一个列表,或read()读取单个或文件中的所有(剩余)字符(默认是全部,使用的参数为字符的数量阅读),但默认的行为(如果直接遍历文件)是一样的用readline,即产生从文件的下一行。

您可以结合起来,与enumerate再弄迭代产生每条线沿线数(有号码的第一线0,除非你指定enumeratestart参数),或获取特定的行:

>>> f = open("test.txt")
>>> lines = enumerate(f)
>>> next(lines)
(0, 'first line\n')
>>> next(lines)
(1, 'second line\n')
>>> next(lines)
(2, 'third line\n')

>>> f = open("test.txt")
>>> lines = enumerate(f)
>>> next(l for i, l in lines if i == 3)
'fourth line\n'

另外还有一个seek方法,它可以被用来跳转到文件中的特定字符,这是“复位”的文件到第一位置(或者重新打开它)是有用的,但在查找特定多没有帮助行,除非你知道每行的确切长度。(见下文)

如果你想“读任意顺序线”最简单的方法就是实际读取所有的行成,用列表readlines,然后访问该列表中的项目(前提是你的文件不是太大)。

>>> f = open("test.txt")
>>> lines = f.readlines()
>>> lines[3]
'fourth line\n'
>>> lines[1]
'second line\n'

我的目标是读几GB的大文件的大小,几十万行。

由于Python的知道在哪里线两端,并且因此是一个特定的行开始,是统计数量的唯一方法\n遇到的人物,还有周围的读取整个文件没有办法。如果该文件是非常大的,你要反复读线出故障,它可能是有意义的读取文件一次一行的时间,存储在字典中的每一行的起始位置。之后,您可以使用seek快速跳转到,然后读一个特定的行。

f = open("test.txt")
total = 1
lines = {}
for i, line in enumerate(f):
    lines[i] = total - 1
    total += len(line)
# jump to and read individual lines
f.seek(lines[3])
print(f.readline())
f.seek(lines[0])
print(f.readline())

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章