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.
This program might do what you want:
def fetch_one_line(filename, linenumber):
with open(filename) as handle:
for n, line in enumerate(handle, 1):
if n == linenumber:
return line
print("OOPS! There aren't enough lines in the file")
return None
my_line = fetch_one_line('input.txt', 5)
print(repr(my_line))
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.