在python中读取用户给定的起始位置和结束位置之间的文本文件

2024-10-01 15:29:31 发布

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

我有一个巨大的文本文件,我想从中有选择地读几行。 使用tell()我知道我想读取的位置。在

在文件的两个位置之间我能读到吗? 像文件.read(开始,结束)

或者,阅读包含beginPos的行号和包含endPos的行号之间的所有文本?在


Tags: 文件文本read文本文件行号选择地tellendpos
3条回答

你看过使用内存映射吗?(http://docs.python.org/library/mmap.html)在

一旦有了文件的内存映射,就可以像对字符串(或列表)那样对其进行切片,而不必将整个文件读入内存。在

如果你只读一次文件的一个部分,这可能是不必要的复杂性,但如果你要做大量的IO,它可以使它更容易管理。在

来自python文档:

import mmap

# write a simple example file
with open("hello.txt", "wb") as f:
    f.write("Hello Python!\n")

with open("hello.txt", "r+b") as f:
    # memory-map the file, size 0 means whole file
    map = mmap.mmap(f.fileno(), 0)
    # read content via standard file methods
    print map.readline()  # prints "Hello Python!"
    # read content via slice notation
    print map[:5]  # prints "Hello"
    # update content using slice notation;
    # note that new content must have same size
    map[6:] = " world!\n"
    # ... and read again using standard file methods
    map.seek(0)
    print map.readline()  # prints "Hello  world!"
    # close the map
    map.close()

您需要先打开文件fileobj.seek(beginPos),然后fileobj.read(endPos-beginPos)

如果现在是起点(使用tell())和结束点,只需做一个file.read(end-start),它将读取end-start字节。如果开始时偏移量不正确,请先使用seek()方法(file.seek(start))。在

相关问题 更多 >

    热门问题