Title pretty much says it all: I've spent over a day figuring out how to fetch a single line of text out of a large text file through inputting its line number, without success. So far, it seems like the only solutions people are talking about online load the entire text file into a list, but it's simply too large to do so. The structure of the .txt file I'm working with is literally just a big listing of urls, one per line.
I've tried using handle.readline()
, but that didn't help the pinpointing of the specific line. Because the file is so large, I can't really justify loading all of its lines into memory using the handle.readlines()
method, so that's a bust as well. I tried to write a function using a for index,line in enumerate(handle)
as found online, but that weirdly returns None
. Any help is appreciated.
EDIT: Some code below that does not work:
fh = open("file.txt","a+")
def offsetfunc(handle,lineNum):
line_offset = []
offset = 0
for line in handle:
line_offset.append(offset)
offset += len(line)
handle.seek(line_offset[lineNum-1],0)
offsetfunc(fh,1) #Returns IndexError
print(fh.readline()) #Presumably would be viable, if the previous statement worked?
Also, using the linecache
technique loads the file into memory, so yeah, that's non-viable, too.