gpt4 book ai didi

Python 文件 io 缓冲

转载 作者:行者123 更新时间:2023-12-04 17:51:58 27 4
gpt4 key购买 nike

我需要多次遍历几个文本文件的行。目前这是通过多个

with open("file.txt") as f: 
for line in f:
# do something

虽然性能还不是问题,但我只想将文件读入 io.StringIO 缓冲区一次,然后使用它。

Python io 文档:

这是一个工作片段

import io
sio = io.StringIO( open("file.txt").read() )
for line in sio:
print(line)
sio.seek(0)
for line in sio:
print(line)
sio.close()

或将其包装在 with 中声明context manager

import io
with io.StringIO( open("file.txt").read() ) as sio:
for line in sio:
print(line)
sio.seek(0)
for line in sio:
print(line)
#sio.close()

问题

  1. 这是一种“好的”方法吗?有哪些替代方法?
  2. 用于读取文件的文件对象会发生什么情况(无法通过这种方式显式close())?
  3. 我在哪里可以阅读更多关于 Python 的 io 缓冲的信息(我想我读到了一些关于 Python 通过自动缓冲优化多个文件访问的内容)?

最佳答案

你现在的做法已经是对的了。引用这个答案:How to read large file, line by line in python

The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered IO and memory management so you don't have to worry about large files.

关于Python 文件 io 缓冲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44028013/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com