source =/tmp/src 包含a,b,c,d文件 destinations ='/ one','/ two'Python - 什么是我能够将文件从源文件夹复制到多个目标的最快方式
,所以我想复制文件A,b,C,d到两个目的地 '/一个' 和 '二'
像
source = '/tmp/src'
destinations = []
def copy_files_multiple_dest(source,destinations)
吧? 现在,我将如何通过所有目的地
source =/tmp/src 包含a,b,c,d文件 destinations ='/ one','/ two'Python - 什么是我能够将文件从源文件夹复制到多个目标的最快方式
,所以我想复制文件A,b,C,d到两个目的地 '/一个' 和 '二'
像
source = '/tmp/src'
destinations = []
def copy_files_multiple_dest(source,destinations)
吧? 现在,我将如何通过所有目的地
怎么像循环:
import os
import shutil
source = '/tmp/src/'
destinations = []
def copy_files_multiple_dest(source,destinations):
sfiles = os.listdir(source) # list of all files in source
for f in sfiles:
for dest in destinations:
shutil.copy(os.path.join(source,f), dest)
我不知道它是最快,但它应该做的工作。
我得到错误[Errno 21]是一个目录:'/ tmp/1 /',当目的地= ['/ tmp/1 /','/ tmp/2 /']时,代码被追加到您的上面 – kamal 2012-02-03 23:56:00
@kamal,如错误消息所示,您正尝试移动一个目录。你可以在移动函数前添加一个条件:if os.path.isfile(dest):.... – yurib 2012-02-04 08:58:10
我不得不使用.strip(),因为argparse只支持字符串而不是列表。在我的代码中,我将空间分隔的目录路径保存在列表中 – kamal 2012-02-07 14:06:56
读取源文件只有一次有意义的位置:
def xcopy_to_multiple_destinations(srcDir, destinations):
for filename in os.listdir(srcDir):
with open(os.path.join(srcDir, filename), "rb") as srcFile:
for destDir in destinations:
with open(os.path.join(destDir, filename), "wb") as destFile:
# ...copy bytes from srcFile to destFile...
如果你想递归地复制,使用os.walk
(见其他问题:Python recursive folder read)。您可以相应地调整解决方案。
请注意,“最快”是一个广义术语。例如,硬连接应该更快;或者使用适合文件系统的写时复制。
os包是通常的方式来得到,但看看这个新项目https://github.com/amoffat/pbs。 那么你可能只是这样做:
import pbs
destinations =['/one', '/two']
for destination in destinations:
pbs.copy("-R", '/tmp/src', destination)
也许不是最快的,但既然你说的文件将不会发散肯定赢得选美比赛
我收到错误:请参阅内联代码 – kamal 2012-02-06 04:11:57
,你可以硬连接它们。你不需要python,这里是我如何在bash中做到这一点。
dests=(a b c d)
for dest in "${dests[@]}"; do
cp -rl /source/root "$dest"
done
如果它必须是蟒蛇,看os.link
和模块中的其他功能。
文件是否需要分歧?如果您100%确定复制后它们始终保持不变,您可能会注意到硬链接。 – Daenyth 2012-02-01 22:19:18
源代码保持不变,因为它由'apt-get install'填充,并且存储在repo文件夹中,所有文件都打包在.deb文件中 – kamal 2012-02-01 23:14:32