加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 你可以将文件内容转换为文件对象吗?

发布时间:2020-12-20 11:29:06 所属栏目:Python 来源:网络整理
导读:我有一个函数期望一个文件对象,简化示例: def process(fd): print fd.read() 通常称为: fd = open('myfile',mode='r')process(fd) 我无法更改此功能,并且我已经在内存中拥有该文件的内容.有没有办法将文件内容转换为文件对象而不将其写入磁盘,所以我可以这
我有一个函数期望一个文件对象,简化示例:

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包中 – 您应该使用io import StringIO而不是StringIO import StringIO.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读