[英]Python 3 - Looking up line in large text file by line number
標題幾乎說明了一切:我花了整整一天的時間來弄清楚如何通過輸入行號從大型文本文件中提取一行文本,但是沒有成功。 到目前為止,似乎人們正在討論的唯一解決方案是將整個文本文件在線加載到列表中,但是這樣做太大了。 我正在使用的.txt文件的結構實際上只是一大堆url,每行一個。
我試過使用handle.readline()
,但這並沒有幫助您確定特定的行。 由於文件太大,因此我無法真正使用handle.readlines()
方法將其所有行都加載到內存中,因此也很handle.readlines()
。 我嘗試使用在線發現的for index,line in enumerate(handle)
的for index,line in enumerate(handle)
編寫函數,但是奇怪地返回None
。 任何幫助表示贊賞。
編輯:下面的某些代碼不起作用:
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?
此外,使用linecache
技術加載文件到內存中,這樣啊,這是不能存活了。
該程序可能會執行您想要的操作:
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.