【问题标题】:How to convert fileData from str to file type in Python?如何在 Python 中将 fileData 从 str 转换为文件类型?
【发布时间】:2015-01-17 07:27:53
【问题描述】:

我有这个文件数据,我从 API 读取为 base64 并使用以下内容转换为常规文件数据:

base64FileData = attachmentObj.data['data']
fileData = base64.urlsafe_b64decode(base64FileData.encode('UTF-8'))
print type(fileData)  # prints out <type 'str'>

由于我需要二进制文件来进一步处理它,然后我可以将它存储并读回如下:

print type(fileData)  # prints out <type 'str'>
with open('thefile.pdf', 'w') as f:
    f.write(fileData)
with open('thefile.pdf', 'rb') as f:
    print type(f)  # prints out <type 'file'>, which I actually need.

这行得通,但是没有必要实际存储文件,这似乎是我见过的最糟糕的代码之一。

有人知道我如何将初始 fileData 转换为类型 'file' 而不存储它并将其读回吗?欢迎所有提示!

【问题讨论】:

  • 这真的没有意义。将数据写入文件不会“将其转换为二进制文件”。您是说您需要能够为某些仅适用于文件的函数提供文件句柄吗?
  • @AndrewMedico - 问题是在我使用的库中,有一个测试可以执行if type(fileData) is str:。如果它是一个字符串,它认为它是一个文件名并尝试使用常规 Python open() 打开文件。因此我需要文件数据的类型为file,而不是str 类型。我可以通过使用open() 写入文件然后再次打开同一个文件来执行此操作。但一定有更好的办法..

标签: python string io binary


【解决方案1】:

查看StringIO / cStringIO modules。它们为内存中的现有缓冲区(字符串)提供文件接口。这将使您无需编写临时文件即可将数据传递到库。

例如:

import StringIO

...

base64FileData = attachmentObj.data['data']
fileData = base64.urlsafe_b64decode(base64FileData.encode('UTF-8'))

memoryFile = StringIO.StringIO(fileData)

someFunctionThatOperatesOnFileObjects(memoryFile)

【讨论】:

    猜你喜欢
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2014-11-25
    相关资源
    最近更新 更多