简体   繁体   中英

Loading the nth line of a txt file in python without loading the whole file

I have a large txt file that is split into lines. I want to load the nth line of this file for use in a for loop in my code. I can't however load the whole array then slice it because of the RAM (the whole file is like 500GB.). Any help would be much appreciated.

You can use a for-loop to iterate over the lines.

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

When iterating over the file, you only have the current line in memory.

The python enumerate function is your go to here. This is because it goes through all of the data without loading everything into memory.

Example code to load the data from line 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM