如何在 Python 中创建假文本文件 [英] How to create fake text file in Python

查看:70
本文介绍了如何在 Python 中创建假文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 中创建一个包含文本的假文件对象?我正在尝试为接收文件对象并通过 readlines() 检索文本的方法编写单元测试,然后进行一些文本操作.请注意,我无法在文件系统上创建实际文件.解决方案必须与 Python 2.7.3 兼容.

How can I create a fake file object in Python that contains text? I'm trying to write unit tests for a method that takes in a file object and retrieves the text via readlines() then do some text manipulation. Please note I can't create an actual file on the file system. The solution has to be compatible with Python 2.7.3.

推荐答案

这正是 StringIO/cStringIO(重命名为 io.StringIO in Python 3) 是为了.

This is exactly what StringIO/cStringIO (renamed to io.StringIO in Python 3) is for.

这篇关于如何在 Python 中创建假文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆