python3在大文本文件中逐行查找numb

2024-06-26 14:58:44 发布

您现在位置:Python中文网/ 问答频道 /正文

标题几乎说明了一切:我花了一天的时间研究如何通过输入一个大文本文件的行号从中提取一行文本,但没有成功。到目前为止,人们谈论的唯一在线解决方案似乎是将整个文本文件加载到一个列表中,但它实在太大了。 我正在使用的.txt文件的结构实际上只是一个很大的URL列表,每行一个。你知道吗

我试过使用handle.readline(),但这无助于确定具体的行。因为这个文件太大了,我不能用handle.readlines()方法将它的所有行加载到内存中,所以这也是一个错误。我试着用在线找到的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技术将文件加载到内存中,所以是的,这也是不可行的。你知道吗


Tags: 文件内存intxt标题列表forreadline
1条回答
网友
1楼 · 发布于 2024-06-26 14:58:44

此程序可能会执行您想要的操作:

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))

相关问题 更多 >