在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()
3 个回答
2
如果你只是想移动一个文件夹,可以用shutil.move这个方法。这个操作会非常快(如果在同一个文件系统上),因为它其实就是一个重命名的过程。
3
编辑:
在我自己感到困惑的时候(JoshD 帮我解决了这个问题),我忘了 shutil.move
这个功能可以处理文件夹,所以你可以(而且应该)直接用它来批量移动你的文件夹。
4
你现在使用的是什么平台?真的必须用Python吗?如果不一定要用Python的话,你可以直接使用系统自带的工具,比如在*nix系统上用mv
命令,或者在Windows上用move
命令。
$ 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