【问题标题】:How to create fake text file in Python如何在 Python 中创建假文本文件
【发布时间】:2012-08-03 17:28:11
【问题描述】:

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

【问题讨论】:

    标签: python python-2.7 readlines


    【解决方案1】:

    这正是 StringIO/cStringIO(在 Python 3 中重命名为 io.StringIO)的用途。

    【讨论】:

    • 解决方案必须兼容 Python 2.7.3
    • @user1454693 StringIO 版本是……还是您使用的 2.7.3 与世界其他地方不同?
    • @user1454693 StringIO 兼容 2.7.3 及以上版本。
    【解决方案2】:

    或者你可以很容易地自己实现它,特别是因为你只需要readlines()

    class FileSpoof:
         def __init__(self,my_text):
             self.my_text = my_text
         def readlines(self):
             return self.my_text.splitlines()
    

    然后就这样称呼它:

    somefake = FileSpoof("This is a bunch\nOf Text!")
    print somefake.readlines()
    

    也就是说,另一个答案可能更正确。

    【讨论】:

      【解决方案3】:

      在 Python3 中

      import io
      fake_file = io.StringIO("your text goes here") # takes string as arg
      fake_file.read() # you can use fake_file object to do whatever you want
      

      在 Python2 中

      import io
      fake_file = io.StringIO(u"your text goes here") # takes unicode as argument
      fake_file.read()  # you can use fake_file object to do whatever you want
      

      更多信息请查看文档here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-29
        • 2012-01-25
        • 1970-01-01
        • 2015-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多