无法打开 python 编写的 PDF 文件
Unable to open PDF file written by python
在我的 Python 代码中,我收到了一个 InMemoryUploadedFile
文件,然后我试图将该文件保存在磁盘上。它说该文件已成功存储,但是当我尝试打开该文件时,出现此错误:
这是我尝试使用的代码片段
with Path("check.pdf").open(mode="wb") as output_file:
output_file.write(fileToParse.read())
我之前试过的另一个代码是这个:
outfd, filePath = tempfile.mkstemp(suffix='check.pdf', dir=os.getcwd())
with open(filePath, "wb") as dest:
dest.write(fileToParse)
os.close(outfd)
在这两种情况下,我都会遇到同样的错误。我检查了不同的帖子,甚至在这里,第一个解决方案适用于很多人。但我不知道为什么它没有为我存储正确的文件。
我收到的文件类型 fileToParse
是 <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
和 fileToParse.read()
returns <class 'bytes'>
Can anyone tell me what am I doing wrong here?
我在 this Answer 的帮助下解决了我的问题,并做了一些小改动。这是对我有用的代码。
import tempfile, os
outfd, filePath = tempfile.mkstemp(suffix=fileToParse.name, dir=os.getcwd())
with open(filePath, 'wb+') as destination:
for chunk in fileToParse.chunks():
destination.write(chunk)
os.close(outfd)
在我的 Python 代码中,我收到了一个 InMemoryUploadedFile
文件,然后我试图将该文件保存在磁盘上。它说该文件已成功存储,但是当我尝试打开该文件时,出现此错误:
这是我尝试使用的代码片段
with Path("check.pdf").open(mode="wb") as output_file:
output_file.write(fileToParse.read())
我之前试过的另一个代码是这个:
outfd, filePath = tempfile.mkstemp(suffix='check.pdf', dir=os.getcwd())
with open(filePath, "wb") as dest:
dest.write(fileToParse)
os.close(outfd)
在这两种情况下,我都会遇到同样的错误。我检查了不同的帖子,甚至在这里,第一个解决方案适用于很多人。但我不知道为什么它没有为我存储正确的文件。
我收到的文件类型 fileToParse
是 <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
和 fileToParse.read()
returns <class 'bytes'>
Can anyone tell me what am I doing wrong here?
我在 this Answer 的帮助下解决了我的问题,并做了一些小改动。这是对我有用的代码。
import tempfile, os
outfd, filePath = tempfile.mkstemp(suffix=fileToParse.name, dir=os.getcwd())
with open(filePath, 'wb+') as destination:
for chunk in fileToParse.chunks():
destination.write(chunk)
os.close(outfd)