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

2024-04-27 03:27:16 发布

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

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

我想是因为我一次只能移动一个文件。我想如果我同时将所有文件从一个目录移动到另一个目录,我可以加快速度。有办法吗?

如果这不是我慢下来的原因,我怎么能加快速度呢?

更新:

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

# 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()

Tags: 文件topathinfromimportsrcmove
3条回答

如果只想移动目录,可以使用shuil.move。它会非常快(如果它在同一个文件系统上的话),因为它只是一个重命名操作。

编辑:

在我自己的混乱状态下(JoshD帮了我一把),我忘记了shutil.move接受目录,所以您可以(而且应该)使用它将目录作为批处理移动。

你在哪个站台?它真的必须是Python吗?如果没有,您可以简单地使用诸如mv(*nix)或move(windows)之类的系统工具。

$ stat -c "%s" file
382849574

$ time python -c 'import shutil;shutil.move("file","/tmp")'

real    0m29.698s
user    0m0.349s 
sys     0m1.862s 

$ time mv file /tmp

real    0m29.149s
user    0m0.011s 
sys     0m1.607s 

$ time python -c 'import shutil;shutil.move("file","/tmp")'

real    0m30.349s
user    0m0.349s 
sys     0m2.015s 

$ time mv file /tmp

real    0m28.292s
user    0m0.015s 
sys     0m1.702s 

$ cat test.py
#!/usr/bin/env python
import shutil
shutil.move("file","/tmp")
shutil.move("/tmp/file",".")

$ cat test.sh
#!/bin/bash
mv file /tmp
mv /tmp/file .

# time python test.py

real    1m1.175s
user    0m0.641s
sys     0m4.110s

$ time bash test.sh

real    1m1.040s
user    0m0.026s
sys     0m3.242s

$ time python test.py

real    1m3.348s
user    0m0.659s
sys     0m4.024s

$ time bash test.sh

real    1m1.740s
user    0m0.017s
sys     0m3.276s

相关问题 更多 >