只压缩Python中的文件

2024-04-23 07:45:13 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在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…)。在

有没有一种方法可以直接添加文件,而不需要文件夹,这样当我解压缩时,我就可以直接得到文件了?非常感谢你!在


Tags: 文件函数目录文件夹modeaswithtempfile
2条回答

尝试使用arcname参数来zf.write

zf.write(tempPath, arcname='Users/mrb0/Documents/things.txt')

如果不了解程序的更多信息,您可能会发现从最外层循环中的file变量获取arcname,而不是从tempPath派生一个新名称。在

尝试给出arcname:

from os import path

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,arcname=path.basename(tempPath))

zf.close()

使用os.path.basename可以从路径中获取文件名。根据zipfile文档,arcname的默认值是不带驱动器号和删除前导路径分隔符的filename。在

相关问题 更多 >