Python 中的多任务处理、重新格式化和移动

Multitasking in Python, Reformat and Move

我有很多文件夹。我想制作 .zip 格式的文件并将它们移动到另一个目录:

    for (dir, dirs, files) in os.walk(directory):
        for filename in files:
             # make zip files
             if filename.endswith(".zip"):
                # move created zip files
                os.rename(dir + '/' + filename, new + '/' + directory + '/' + filename)

问题是,在生成 zip 文件后,程序找不到具有 zip 扩展名的已创建文件。我想创建一个 zip 格式并将其移动到另一个文件夹。

您可以使用 shutil 库:

import shutil
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

shutil.move(src, dst)

Recursively move a file or directory (src) to another location (dst).

If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.

If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied (using shutil.copy2()) to dst and then removed.


您也可以使用 shutil 作为归档文件:

shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])

Create an archive file (such as zip or tar) and return its name.

有关详细信息,请阅读 shutil documentation