Python を使用してファイルのディレクトリ全体を既存のディレクトリにコピーするにはどうすればよいですか?
質問
という名前のディレクトリを含むディレクトリから次のコードを実行します。 bar
(1 つ以上のファイルを含む) およびという名前のディレクトリ baz
(1 つ以上のファイルも含まれます)。という名前のディレクトリが存在しないことを確認してください。 foo
.
import shutil
shutil.copytree('bar', 'foo')
shutil.copytree('baz', 'foo')
次の場合は失敗します:
$ python copytree_test.py
Traceback (most recent call last):
File "copytree_test.py", line 5, in <module>
shutil.copytree('baz', 'foo')
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/shutil.py", line 110, in copytree
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.py", line 172, in makedirs
OSError: [Errno 17] File exists: 'foo'
これを次のように入力したのと同じように機能させたいと考えています。
$ mkdir foo
$ cp bar/* foo/
$ cp baz/* foo/
使用する必要がありますか shutil.copy()
各ファイルをコピーするには baz
の中へ foo
?(すでに「bar」の内容を「foo」にコピーした後、 shutil.copytree()
?) それとも、もっと簡単/より良い方法はありますか?
解決
この規格の制限は、 shutil.copytree
恣意的で迷惑なようです。回避策:
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
標準のコピーツリーと完全に一致しているわけではないことに注意してください。
- それは名誉ではありません
symlinks
そしてignore
のルートディレクトリのパラメータsrc
木; - それは上がらない
shutil.Error
ルートレベルでのエラーの場合src
; - サブツリーのコピー中にエラーが発生した場合、
shutil.Error
他のサブツリーをコピーして単一の結合を生成する代わりに、そのサブツリーに対してshutil.Error
.
他のヒント
これは標準ライブラリの一部であるソリューションです。
from distutils.dir_util import copy_tree
copy_tree("/a/b/c", "/x/y/z")
この同様の質問を参照してください。
上記の関数が常にソースから宛先にファイルをコピーしようとする関数に対する atzz の回答をわずかに改善しました。
def copytree(src, dst, symlinks=False, ignore=None):
if not os.path.exists(dst):
os.makedirs(dst)
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
shutil.copy2(s, d)
上記の実装では
- 出力ディレクトリが存在しない場合は作成します
- 独自のメソッドを再帰的に呼び出してディレクトリのコピーを実行します。
- ファイルを実際にコピーするようになったら、ファイルが変更されているかどうかを確認するだけで、コピーする必要があります。
私は上記の関数をsconsビルドとともに使用しています。コンパイルするたびにファイルセット全体をコピーする必要がないため、非常に役立ちました。ただし、変更されたファイルのみです。
atzz と Mital Vora からインスピレーションを得たマージ 1:
#!/usr/bin/python
import os
import shutil
import stat
def copytree(src, dst, symlinks = False, ignore = None):
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x for x in lst if x not in excl]
for item in lst:
s = os.path.join(src, item)
d = os.path.join(dst, item)
if symlinks and os.path.islink(s):
if os.path.lexists(d):
os.remove(d)
os.symlink(os.readlink(s), d)
try:
st = os.lstat(s)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(d, mode)
except:
pass # lchmod not available
elif os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
- と同じ動作 シャティル.コピーツリー, 、 と シンボリックリンク そして 無視する パラメーター
- ディレクトリ宛先構造が存在しない場合は作成します
- こうすれば失敗しない 夏時間 もう存在している
ドキュメントは明示的にその先のディレクトリを述べるに存在している必要がありますのます:
dst
で指定された先のディレクトリは、まだ存在していなければなりません。それは親ディレクトリを逃すと同様に作成されます。
私はあなたの最善の策は、第二およびすべての必然的なディレクトリをos.walk
ことだと思い、 copy2
のディレクトリとファイルやディレクトリの追加copystat
を行います。すべてのその後のようにドキュメントで説明しない何copytree
正確です。それとも、代わりにcopy
の各ディレクトリ/ファイルとcopystat
をos.listdir
とos.walk
可能性があります。
あなたはshutil
を変更し、
shutil
このライン315
上での私のバージョンで)効果を得ることができます
変更
os.makedirs(dst)
タグへ
os.makedirs(dst,exist_ok=True)
このはatzzが提供するオリジナルの最良の答えからインスピレーションを得ている、私は、ファイル/フォルダのロジックを交換してください追加します。だから、実際にマージしますが、新しい1既存のファイル/フォルダのコピーを削除しません。
import shutil
import os
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.exists(d):
try:
shutil.rmtree(d)
except Exception as e:
print e
os.unlink(d)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
#shutil.rmtree(src)
は移動機能にするrmtreeのコメントを外します。
私が引き受ける最速かつ最も簡単な方法...システムはコマンドを呼び出すのpython持っているだろう。
例..
import os
cmd = '<command line call>'
os.system(cmd)
タールと解凍....ディレクトリをgzip圧縮し、所望の場所にあるディレクトリにuntarし。
yahの?
ここでは、同じタスクの私のバージョンは::
import os, glob, shutil
def make_dir(path):
if not os.path.isdir(path):
os.mkdir(path)
def copy_dir(source_item, destination_item):
if os.path.isdir(source_item):
make_dir(destination_item)
sub_items = glob.glob(source_item + '/*')
for sub_item in sub_items:
copy_dir(sub_item, destination_item + '/' + sub_item.split('/')[-1])
else:
shutil.copy(source_item, destination_item)
ここでは、より密接にdistutils.file_util.copy_file
を模倣このスレッドに触発されたバージョンです。
updateonly
に記載されていない限り、 dst
がTrue場合はブール値である、唯一のforceupdate
内の既存のファイルより新しい修正日付のファイルをコピーします。
ignore
とforceupdate
はのsrc
に対する相対ファイル名やフォルダ/ファイル名のののリストを期待し、Unixスタイルを受け入れることはglob
またはfnmatch
に似ワイルドカードます。
この関数は、コピー(またはTrue場合dryrun
場合はコピーされる)ファイルのリストを返します。
import os
import shutil
import fnmatch
import stat
import itertools
def copyToDir(src, dst, updateonly=True, symlinks=True, ignore=None, forceupdate=None, dryrun=False):
def copySymLink(srclink, destlink):
if os.path.lexists(destlink):
os.remove(destlink)
os.symlink(os.readlink(srclink), destlink)
try:
st = os.lstat(srclink)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(destlink, mode)
except OSError:
pass # lchmod not available
fc = []
if not os.path.exists(dst) and not dryrun:
os.makedirs(dst)
shutil.copystat(src, dst)
if ignore is not None:
ignorepatterns = [os.path.join(src, *x.split('/')) for x in ignore]
else:
ignorepatterns = []
if forceupdate is not None:
forceupdatepatterns = [os.path.join(src, *x.split('/')) for x in forceupdate]
else:
forceupdatepatterns = []
srclen = len(src)
for root, dirs, files in os.walk(src):
fullsrcfiles = [os.path.join(root, x) for x in files]
t = root[srclen+1:]
dstroot = os.path.join(dst, t)
fulldstfiles = [os.path.join(dstroot, x) for x in files]
excludefiles = list(itertools.chain.from_iterable([fnmatch.filter(fullsrcfiles, pattern) for pattern in ignorepatterns]))
forceupdatefiles = list(itertools.chain.from_iterable([fnmatch.filter(fullsrcfiles, pattern) for pattern in forceupdatepatterns]))
for directory in dirs:
fullsrcdir = os.path.join(src, directory)
fulldstdir = os.path.join(dstroot, directory)
if os.path.islink(fullsrcdir):
if symlinks and dryrun is False:
copySymLink(fullsrcdir, fulldstdir)
else:
if not os.path.exists(directory) and dryrun is False:
os.makedirs(os.path.join(dst, dir))
shutil.copystat(src, dst)
for s,d in zip(fullsrcfiles, fulldstfiles):
if s not in excludefiles:
if updateonly:
go = False
if os.path.isfile(d):
srcdate = os.stat(s).st_mtime
dstdate = os.stat(d).st_mtime
if srcdate > dstdate:
go = True
else:
go = True
if s in forceupdatefiles:
go = True
if go is True:
fc.append(d)
if not dryrun:
if os.path.islink(s) and symlinks is True:
copySymLink(s, d)
else:
shutil.copy2(s, d)
else:
fc.append(d)
if not dryrun:
if os.path.islink(s) and symlinks is True:
copySymLink(s, d)
else:
shutil.copy2(s, d)
return fc
以前のソリューションは、任意の通知や例外なくsrc
を上書きすることがありdst
いくつかの問題があります。
私はシリルPontvieuxのバージョンにcopy.predict_error
主にベースの前にエラーを予測するcopytree
メソッドを追加します。
あなたはすべてのエラーを修正するまでpredict_error
を実行したときに例外が別ずつ引き上げ見たい場合を除き、最高で最初にすべてのエラーを予測するcopytree
を使用します。
def predict_error(src, dst):
if os.path.exists(dst):
src_isdir = os.path.isdir(src)
dst_isdir = os.path.isdir(dst)
if src_isdir and dst_isdir:
pass
elif src_isdir and not dst_isdir:
yield {dst:'src is dir but dst is file.'}
elif not src_isdir and dst_isdir:
yield {dst:'src is file but dst is dir.'}
else:
yield {dst:'already exists a file with same name in dst'}
if os.path.isdir(src):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
for e in predict_error(s, d):
yield e
def copytree(src, dst, symlinks=False, ignore=None, overwrite=False):
'''
would overwrite if src and dst are both file
but would not use folder overwrite file, or viceverse
'''
if not overwrite:
errors = list(predict_error(src, dst))
if errors:
raise Exception('copy would overwrite some file, error detail:%s' % errors)
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x for x in lst if x not in excl]
for item in lst:
s = os.path.join(src, item)
d = os.path.join(dst, item)
if symlinks and os.path.islink(s):
if os.path.lexists(d):
os.remove(d)
os.symlink(os.readlink(s), d)
try:
st = os.lstat(s)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(d, mode)
except:
pass # lchmod not available
elif os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
if not overwrite:
if os.path.exists(d):
continue
shutil.copy2(s, d)
ここでの問題で私のパスです。私は、元の機能を維持するためにcopytreeのソースコードを変更しますが、ディレクトリがすでに存在する場合、今エラーは発生しません。私はそれが既存のファイルを上書きしないように、また、それを変更したが、これは自分のアプリケーションのために重要だったので、むしろ、両方のコピー、変更された名前の1を保持します。
import shutil
import os
def _copytree(src, dst, symlinks=False, ignore=None):
"""
This is an improved version of shutil.copytree which allows writing to
existing folders and does not overwrite existing files but instead appends
a ~1 to the file name and adds it to the destination path.
"""
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
i = 1
while os.path.exists(dstname) and not os.path.isdir(dstname):
parts = name.split('.')
file_name = ''
file_extension = parts[-1]
# make a new file name inserting ~1 between name and extension
for j in range(len(parts)-1):
file_name += parts[j]
if j < len(parts)-2:
file_name += '.'
suffix = file_name + '~' + str(i) + '.' + file_extension
dstname = os.path.join(dst, suffix)
i+=1
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
_copytree(srcname, dstname, symlinks, ignore)
else:
shutil.copy2(srcname, dstname)
except (IOError, os.error) as why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except BaseException as err:
errors.extend(err.args[0])
try:
shutil.copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
raise BaseException(errors)
このお試しくださいます:
import os,shutil
def copydir(src, dst):
h = os.getcwd()
src = r"{}".format(src)
if not os.path.isdir(dst):
print("\n[!] No Such directory: ["+dst+"] !!!")
exit(1)
if not os.path.isdir(src):
print("\n[!] No Such directory: ["+src+"] !!!")
exit(1)
if "\\" in src:
c = "\\"
tsrc = src.split("\\")[-1:][0]
else:
c = "/"
tsrc = src.split("/")[-1:][0]
os.chdir(dst)
if os.path.isdir(tsrc):
print("\n[!] The Directory Is already exists !!!")
exit(1)
try:
os.mkdir(tsrc)
except WindowsError:
print("\n[!] Error: In[ {} ]\nPlease Check Your Dirctory Path !!!".format(src))
exit(1)
os.chdir(h)
files = []
for i in os.listdir(src):
files.append(src+c+i)
if len(files) > 0:
for i in files:
if not os.path.isdir(i):
shutil.copy2(i, dst+c+tsrc)
print("\n[*] Done ! :)")
copydir("c:\folder1", "c:\folder2")