How to create fake text file in Python

前端 未结 3 2216
独厮守ぢ
独厮守ぢ 2021-02-13 03:21

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 readl

相关标签:
3条回答
  • 2021-02-13 04:10

    Or you could implement it yourself pretty easily especially since all you need is readlines():

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

    then just call it like:

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

    That said the other answer is probably more correct.

    0 讨论(0)
  • 2021-02-13 04:13

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

    0 讨论(0)
  • 2021-02-13 04:14

    In 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
    

    In 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
    

    For more info check docs here

    0 讨论(0)
提交回复
热议问题