gpt4 book ai didi

python - 您可以将文件内容转换为文件对象吗?

转载 作者:太空宇宙 更新时间:2023-11-03 13:19:44 24 4
gpt4 key购买 nike

我有一个函数需要一个文件对象,简化示例:

def process(fd):
print fd.read()

通常称为:

fd = open('myfile', mode='r')
process(fd)

我不能改变这个功能,我已经在内存中有了文​​件的内容。有什么方法可以文件内容转换为文件对象而不将其写入磁盘,这样我就可以做这样的事情:

contents = 'The quick brown file'
fd = convert(contents) # ??
process(fd)

最佳答案

您可以使用 StringIO 执行此操作:

This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).

from StringIO import StringIO

def process(fd):
print fd.read()

contents = 'The quick brown file'

buffer = StringIO()
buffer.write(contents)
buffer.seek(0)

process(buffer) # prints "The quick brown file"

请注意,在 Python 3 中它被移动到 io 中包 - 你应该使用 from io import StringIO 而不是 from StringIO import StringIO

关于python - 您可以将文件内容转换为文件对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18293016/

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