【发布时间】:2019-03-07 23:08:51
【问题描述】:
我需要能够创建一个具有指定文件名的临时文件并将数据写入其中,然后将带有文件名的文件与其他文件一起压缩:
fd, path = tempfile.mkstemp(".bin", "filename", "~/path/to/working/directory/")
try:
with os.fdopen(fd, "wb") as tmp:
tmp.write(data)
with ZipFile("zip.zip", "w") as zip:
zip.write("filename")
zip.writestr("file2", file2_str)
zip.writestr("file3", file3_str)
# ...
finally:
os.remove(path)
我想我一定是误解了 mkstemp 的工作原理,我在此处的第一行代码处得到错误:
FileNotFoundError: [Errno 2] No such file or directory: '~/path/to/working/directory/filenameq5st7dey.bin'
在文件添加后缀之前,文件名中似乎添加了一堆垃圾。我试过这个没有后缀,但文件名末尾仍然有垃圾。
除了文件名中的垃圾之外,为什么我会得到一个找不到文件的错误,而不是在我的目录中创建一个具有该名称的临时文件(加上垃圾)?
【问题讨论】:
标签: python python-3.x temporary-files mkstemp