尝试只压缩一个目录中的文件

2024-10-01 15:38:32 发布

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

我有路径/home/mine/new,其中包含文件和子目录。我只想压缩该路径中的文件(在“new”路径中),以便压缩后的文件夹包含/new/file1new/file2

我试过了:

import zipfile
import os,glob


def zipfunc(path, myzip):
    for path,dirs, files in os.walk(path):
            for file in files:
                if  os.path.isfile(os.path.join(path,file)):
                    myzip.write(os.path.join(os.path.basename(path), file))


if __name__ == '__main__':
    path=r'/home/ggous/new'
    myzip = zipfile.ZipFile('myzipped.zip', 'w')
    zipfunc(path,myzip)
    myzip.close()

但它给了我一个错误
没有这样的文件或目录新/文件.doc在


Tags: 文件pathinimport路径homenewfor
3条回答

您正在对path变量调用os.path.basename。这意味着,如果您试图压缩文件new/dir1/file1,则删除路径中的new/部分,并以dir1/file1结束,这不是相对于当前目录的有效路径。在

如果您只需删除对os.path.basename的调用,它将正确压缩文件:

myzip.write(os.path.join(path, file))

…虽然这可能不是您在zipfile中想要的路径。如果从顶层目录中启动os.walk,则可能会得到您想要的结果:

^{2}$

考虑到这样的层级结构:

/home/lars/new
  file1
  file2
  dir1/
    file1
    file2
    file3

这将创建一个如下所示的zipfile:

Archive:  myzipped.zip
  Length      Date    Time    Name
    -          -     
       29  11-02-2011 09:14   file1
       29  11-02-2011 09:14   file2
       29  11-02-2011 09:14   dir1/file3
       29  11-02-2011 09:14   dir1/file1
       29  11-02-2011 09:14   dir1/file2
    -                        -
      145                     5 files

如果您的实际目标是只压缩顶层的文件,而不是降到任何子目录中,那么您实际上不需要os.walk。您只需使用os.listdir,和os.path.isfile来确保您处理的是文件而不是子目录。在

这看起来可能是zipfile.ZipFile.write()需要绝对路径的问题,而不是相对路径或不完整路径。在压缩指向的文件之前,请尝试确保路径是绝对路径:

def zipfunc(path, myzip):
    for path,dirs, files in os.walk(path):
            for file in files:
                curpath = os.path.abspath(os.path.join(path, file))
                if  os.path.isfile(curpath):
                    myzip.write(curpath)

这是因为os.walk将下降到子目录中(而您的路径连接逻辑无法正确处理这一点)。如果不想递归到子目录中,请使用glob.glob而不是os.walk

from os import path
import os

directory = r'/home/ggous/new'
for f in os.listdir(directory):
     if path.isfile(f):
         zipfile.write(os.path.basename(f), f)

相关问题 更多 >

    热门问题