python - 文件流 - ValueError : embedded null byte

标签 python python-3.x

我正在尝试通过 HTTP 请求下载 .png 图像并通过 HTTP 将其上传到另一个位置。我的目标是避免将文件保存在磁盘上,以便在内存中进行处理。

我有以下代码:

  1. 下载文件并将其转换为字节数组:
resp = requests.get(
    'http://www.personal.psu.edu/crd5112/photos/PNG%20Example.png',
    stream=True)

img = BytesIO(resp.content)
  1. 将文件上传到远程 HTTP 存储库
data=open(img.getvalue()).read()

r = requests.post(url=url, data=data, headers=headers, auth=HTTPBasicAuth('user', 'user'))

读取字节数组时出现 ValueError 异常“嵌入空字节”。

如果我将文件保存到磁盘并按如下方式加载,则没有错误:

with open('file.png', 'wb') as pic:
  pic.write(img.getvalue())

关于如何在不将文件保存在磁盘上的情况下实现它的任何建议?

最佳答案

我认为嵌入的空字节错误是由支持在您的代码中执行的任何操作的库的文件名输入要求引起的。通过使用 BytesIO 对象,它会将自己呈现给该库,“就好像”它被包装在一个文件中一样。

这是我在尝试使用 tar 文件解决相同问题时使用的示例代码。此代码应该能够满足各种其他库的大多数文件输入要求。

我在这里找到的关键是使用 remote_file.content 周围的 BytesIO 对象作为文件传递到 tarfile.open目的。我尝试的其他技术没有奏效。

from io import BytesIO
import requests
import tarfile

remote_file=requests.get ('https://download.site.com/files/file.tar.gz')

#Extract tarball contents to memory
tar=tarfile.open(fileobj=BytesIO(remote_file.content))
#Optionally print all folders / files within the tarball
print(tar.getnames())
tar.extractall('/home/users/Documents/target_directory/')

这消除了我在使用其他方法时遇到的 ValueError: embedded null byteexpected str, bytes or os.PathLike object, not _io.BytesIO 错误。

关于python - 文件流 - ValueError : embedded null byte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57940548/

相关文章:

python - Sqlalchemy 在时隙中获取行

python - 设置 AnchoredOffsetbox 的线宽和面颜色?

Python导入错误: cannot import name 'literal_eval'

python - 在列表中查找连续值

python - 构建 pygdal : Unknown distribution option: 'use_2to3_fixers' and 'use_2to3_exclude_fixers' 时出错

Jupyter 笔记本中的 Python while 循环未执行

python - 从不同目录导入文件后 Geopandas 不工作

python - 如何在 Python - GEKKO 中构建和打印循环生成的优化值列表?

python - 使用 Python 将 Geojson 转为 shapefile

python - 如何使用 MongoKit 对远程数据库主机进行身份验证?