【问题标题】:Loading the nth line of a txt file in python without loading the whole file在python中加载txt文件的第n行而不加载整个文件
【发布时间】:2021-04-14 07:49:07
【问题描述】:

我有一个大的 txt 文件,它被分成几行。我想加载这个文件的第 n 行,以便在我的代码中的 for 循环中使用。但是,由于 RAM 的原因,我无法加载整个数组然后对其进行切片(整个文件就像 500GB!)。任何帮助将不胜感激。

【问题讨论】:

标签: python memory ram txt


【解决方案1】:

您可以使用 for 循环来遍历这些行。

with open("file.txt") as f:
    for line in f:
        print(line)

遍历文件时,内存中只有当前行。

【讨论】:

    【解决方案2】:

    python 枚举函数是您的首选。这是因为它会遍历所有数据,而不会将所有内容加载到内存中。

    从第 26 行加载数据的示例代码

    line = 26
    f = open(“file”)
    data = None
    for i, item in enumerate(f):
        if i == line - 1:
            data = item
            break
    if data is not None:
        print(data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 2020-06-13
      • 2021-06-17
      相关资源
      最近更新 更多