gpt4 book ai didi

python - 有没有办法在 Python 中快速 move 许多文件?

转载 作者:太空狗 更新时间:2023-10-30 02:14:07 25 4
gpt4 key购买 nike

我有一个小脚本可以在我的照片集中 move 文件,但它运行起来有点慢。

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

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

更新:

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

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

最佳答案

你在什么平台上?它真的必须是 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

关于python - 有没有办法在 Python 中快速 move 许多文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3896451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com