![](/img/trans.png)
[英]Read nth line of importlib.resources.files without loading whole file in memory
[英]Loading the nth line of a txt file in python without loading the whole file
我有一个大的 txt 文件,它被分成几行。 我想加载这个文件的第 n 行,以便在我的代码中的 for 循环中使用。 但是,由于 RAM 的原因,我无法加载整个数组然后对其进行切片(整个文件就像 500GB。)。 任何帮助将非常感激。
您可以使用 for 循环遍历这些行。
with open("file.txt") as f:
for line in f:
print(line)
遍历文件时,您只有 memory 中的当前行。
python 枚举 function 是您的 go 到这里。 这是因为它会遍历所有数据,而不会将所有内容加载到 memory 中。
从第 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.