Python - 读取和打印大 .txt 文件的前 n 行

时间:2021-01-17 00:47:15

标签: python python-3.x rows itertools

我使用 Python3 并且我想读取并打印 .txt 的前 N ​​行(该文件是 40GB+,因此由于 RAM 限制我无法打开它)。我只想了解文件结构(列、变量名、分隔符……)。使用下面的代码,Python 给了我 [] 作为输出(而不是我想要的打印行):

from itertools import islice

with open("filename.txt") as myfile:
    head = list(islice(myfile, 1, 25))
print(head)

我也尝试在文件名旁边添加 'r',但没有成功。我只想能够读取前 N 行(无论是 25 行、5,10 还是 15,我不在乎)。

嗨,下面的回复是针对 .txt 文件(而不是 Python 代码)。我完全改变了我的方法并尝试使用 pd.read_csv 读取最初的 100 行,如下所示:

dfcontact2 = pd.read_csv('filename.txt', sep='|', names=['col1'], nrows=100)
dfcontact2.head(5)

代码输出:

enter image description here

其中第 0 行是变量名称。我在每一行的末尾看不到任何 '\n' 字符,所以我猜文件不是按行结构的,但是为什么输出是按行提供的?我错过了什么?

非常感谢您的时间。 最好的,

2 个答案:

答案 0 :(得分:3)

您的代码看起来不错,所以很可能是您的文件有问题!

文件 myfile.txt(现在是 filename.txt

  • 没有多于一行的内容(您的逻辑会跳过第一行作为 zvone 注释中的注释),所以当从索引中读取时1(第 2 行),您会发现它的计算结果约为

    >>> list(islice(["file line 1"], 1, 25))
    []
    

    更多示例

    >>> list(islice(["file line 1"], 25))  # don't skip line 1
    ['file line 1']
    >>> list(islice(["file line 1", "file line 2"], 1, 25)) # multiple lines
    ['file line 2']
    
  • 确实存在(不引发 FileNotFoundError

    >>> open("foo.missing")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    FileNotFoundError: [Errno 2] No such file or directory: 'foo.missing'
    

测试,代码对我有用,更改为从索引 0 而不是 1 读取

>>> with open("myfile2.txt", 'w') as fh:
...     for x in range(100):
...         fh.write("line {}\n".format(x))
...
[output clipped]
>>> from itertools import islice
>>> with open("myfile2.txt") as fh:
...     head = list(islice(fh, 25))
...
>>> head
['line 0\n', 'line 1\n', 'line 2\n', 'line 3\n', 'line 4\n', 'line 5\n', 'line 6\n', 'line 7\n', 'line 8\n', 'line 9\n', 'line 10\n', 'line 11\n', 'line 12\n', 'line 13\n', 'line 14\n', 'line 15\n', 'line 16\n', 'line 17\n', 'line 18\n', 'line 19\n', 'line 20\n', 'line 21\n', 'line 22\n', 'line 23\n', 'line 24\n']

答案 1 :(得分:-1)

head = []
with open("filename.txt") as myfile
    for _ in range(25):
        head.append(myfile.readline())
print(head)

文件 IO 基于缓存策略。如果太大,整个文件将不会在内存中。如果您readline,则只会缓存该行周围的一些块。

如果失败,我认为该文件不是文本文件或者它不包含\n,所以单个readline耗尽了整个内存。

相关问题