【问题标题】:How to create a file object in python without using open()如何在不使用 open() 的情况下在 python 中创建文件对象
【发布时间】:2015-01-08 22:25:37
【问题描述】:

用例:
我有一个接受文件对象并执行某些操作的方法 doSomething(file),但我无法更改此方法。

现在,要将文件传递给 doSomething,我需要通过 open() 方法打开它,但我没有该文件要存储在 localhost 上,我可以这样做,但我有文件内容和文件名存储在python变量中。有没有办法从这两个变量中获取文件对象?

【问题讨论】:

    标签: file python-2.7 python-3.x


    【解决方案1】:

    StringIO 类是一个类文件类,它将内容存储在内存中。您可以使用您的内容创建一个实例,并将其传递给doSomething(strio)

    来自docs:

    import StringIO
    
    output = StringIO.StringIO()
    output.write('First line.\n')
    print >>output, 'Second line.'
    

    【讨论】:

    • 请注意,您需要在写入后使用output.seek(0),否则获取类文件对象的函数将在最后一次写入之后而不是类文件对象的开头具有偏移量。
    【解决方案2】:

    如果您的数据是 8 位字符串或 Unicode,StringIO 是一个不错的选择。但是,如果您的数据是二进制或 8 位字符串和 Unicode 的混合,那么 StringIO 将失败。在这种情况下,推荐使用 BytesIO。

    import io
    
    your_data = b'\x02\x1b\x92\x1fs\x96\x97\xe8\x01'
    sd = io.BytesIO()
    sd.write(your_data)
    sd.seek(0) # Seek to the beginning
    
    # sd can act like a file handle. Pass it to your function. 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      相关资源
      最近更新 更多