所以我在NamedTemporaryFile函数指定的临时目录中创建了几个文件。在
zf = zipfile.ZipFile( zipPath, mode='w' )
for file in files:
with NamedTemporaryFile(mode='w+b', bufsize=-1, prefix='tmp') as tempFile:
tempPath = tempFile.name
with open(tempPath, 'w') as f:
write stuff to tempPath with contents of the variable 'file'
zf.write(tempPath)
zf.close()
当我使用这些文件的路径添加到zip文件时,temp目录本身就会被压缩。
当我试图解压缩时,我会得到一系列临时文件夹,这些文件夹最终包含了我想要的文件。
(即,我得到文件夹Users,其中包含我的user_id文件夹,其中包含AppData…)。在
有没有一种方法可以直接添加文件,而不需要文件夹,这样当我解压缩时,我就可以直接得到文件了?非常感谢你!在
尝试使用
arcname
参数来zf.write
:如果不了解程序的更多信息,您可能会发现从最外层循环中的
file
变量获取arcname
,而不是从tempPath
派生一个新名称。在尝试给出arcname:
使用
os.path.basename
可以从路径中获取文件名。根据zipfile文档,arcname的默认值是不带驱动器号和删除前导路径分隔符的filename。在相关问题 更多 >
编程相关推荐