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

3 投票
3 回答
3427 浏览
提问于 2025-04-17 02:12

我有一个很大的文本文件,我想从中选择性地读取几行内容。

通过使用tell()函数,我知道我想要读取的内容的位置。

有没有办法可以读取这两个位置之间的所有文本呢?比如说,像file.read(beginPos, endPos)这样。

或者,也可以读取包含beginPos和endPos的行号之间的所有文本吗?

3 个回答

0

你有没有考虑过使用内存映射?(http://docs.python.org/library/mmap.html)

一旦你对文件进行了内存映射,就可以像处理字符串(或列表)一样对它进行切片,而不需要把整个文件都读到内存里。

如果你只是想读取文件的某一部分一次,这样做可能会显得有些复杂,但如果你需要频繁进行输入输出操作,这样会让管理变得简单很多。

来自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()
0

你需要先打开文件,然后用 fileobj.seek(beginPos) 来移动到你想要开始读取的位置。接着,再用 fileobj.read(endPos-beginPos) 来读取从这个位置到结束位置之间的内容。

6

如果你知道开始的位置(用 tell() 可以找到)和结束的位置,你可以直接用 file.read(end-start) 来读取数据,这样就能读取 end-start 字节的数据。如果你一开始的位置不对,先用 seek() 方法(file.seek(start))调整到正确的位置。

撰写回答