有没有办法在 Python 中快速移动多个文件?

all*_*ode 5 python performance file move shutil

我有一个小脚本可以在我的照片集中移动文件,但运行速度有点慢。

我认为这是因为我一次只移动一个文件。我猜如果我同时将所有文件从一个目录移动到另一个目录,我可以加快速度。有没有办法做到这一点?

如果这不是我缓慢的原因,我还能如何加快速度?

更新:

我认为我的问题没有被理解。也许,列出我的源代码将有助于解释:

# ORF is the file extension of the files I want to move;
# These files live in dirs shared by JPEG files,
# which I do not want to move.
import os
import re
from glob import glob
import shutil

DIGITAL_NEGATIVES_DIR = ...
DATE_PATTERN = re.compile('\d{4}-\d\d-\d\d')

# Move a single ORF.
def move_orf(src):
    dir, fn = os.path.split(src)
    shutil.move(src, os.path.join('raw', dir))

# Move all ORFs in a single directory.
def move_orfs_from_dir(src):
    orfs = glob(os.path.join(src, '*.ORF'))
    if not orfs:
        return
    os.mkdir(os.path.join('raw', src))
    print 'Moving %3d ORF files from %s to raw dir.' % (len(orfs), src)
    for orf in orfs:
        move_orf(orf)

# Scan for dirs that contain ORFs that need to be moved, and move them.
def main():
    os.chdir(DIGITAL_NEGATIVES_DIR)
    src_dirs = filter(DATE_PATTERN.match, os.listdir(os.curdir))
    for dir in src_dirs:
        move_orfs_from_dir(dir)

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

Jim*_*som 3

编辑:

在我自己的混乱状态中(JoshD 帮助纠正了这一点),我忘记了shutil.move接受目录,因此您可以(并且应该)使用它来批量移动目录。

  • @movieyoda:我认为您没有移动 20GB 目录然后复制相同的 20GB 目录,是吗?移动(在同一磁盘上)只是重命名。 (11认同)
  • 我认为他想要移动而不是复制......也许吧。在这种情况下,简单的移动比复制然后删除要快**得多**。 (3认同)