欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python读取大文件的坑_如何在Python中读取大文件的特定部分

发布时间:2025/3/15 python 22 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python读取大文件的坑_如何在Python中读取大文件的特定部分 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

Given a large file (hundreds of MB) how would I use Python to quickly read the content between a specific start and end index within the file?

Essentially, I'm looking for a more efficient way of doing:

open(filename).read()[start_index:end_index]

解决方案

You can seek into the file the file and then read a certain amount from there. Seek allows you to get to a specific offset within a file, and then you can limit your read to only the number of bytes in that range.

with open(filename) as fin:

fin.seek(start_index)

data = fin.read(end_index - start_index)

That will only read that data that you're looking for.

总结

以上是生活随笔为你收集整理的python读取大文件的坑_如何在Python中读取大文件的特定部分的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。