web-dev-qa-db-ja.com

Pythonの複数のファイルをコピーします

Pythonを使用して、あるディレクトリにあるすべてのファイルを別のディレクトリにコピーする方法。文字列としてソースパスと宛先パスがあります。

76
hidayat

os.listdir() を使用してソースディレクトリ内のファイルを取得し、 os.path.isfile() を使用して通常のファイル(シンボリックリンクを含む) * nix systems)、および shutil.copy コピーを実行します。

次のコードは、ソースディレクトリから宛先ディレクトリに通常のファイルのみをコピーします(サブディレクトリをコピーしたくないと仮定しています)。

import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
    full_file_name = os.path.join(src, file_name)
    if os.path.isfile(full_file_name):
        shutil.copy(full_file_name, dest)
116
GreenMatt

ツリー全体(サブディレクトリなど)をコピーしたくない場合は、またはglob.glob("path/to/dir/*.*")を使用してすべてのファイル名のリストを取得し、リストをループしてshutil.copyを使用して各ファイルをコピーします。

for filename in glob.glob(os.path.join(source_dir, '*.*')):
    shutil.copy(filename, dest_dir)
26
Steven

Pythonドキュメントのshutil 、特に copytree コマンドを見てください。

10
Doon
import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below

dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")

for filename in os.listdir(dir_src):
    if filename.endswith('.txt'):
        shutil.copy( dir_src + filename, dir_dst)
    print(filename)
4
Isaac
def recursive_copy_files(source_path, destination_path, override=False):
"""
Recursive copies files from source  to destination directory.
:param source_path: source directory
:param destination_path: destination directory
:param override if True all files will be overridden otherwise skip if file exist
:return: count of copied files
"""
files_count = 0
if not os.path.exists(destination_path):
    os.mkdir(destination_path)
items = glob.glob(source_path + '/*')
for item in items:
    if os.path.isdir(item):
        path = os.path.join(destination_path, item.split('/')[-1])
        files_count += recursive_copy_files(source_path=item, destination_path=path, override=override)
    else:
        file = os.path.join(destination_path, item.split('/')[-1])
        if not os.path.exists(file) or override:
            shutil.copyfile(item, file)
            files_count += 1
return files_count

これは、ディレクトリ(サブディレクトリを含む)の内容を一度に1ファイルずつコピーできる再帰コピー機能の別の例です。この問題を解決するために使用しました。

import os
import shutil

def recursive_copy(src, dest):
    """
    Copy each file from src dir to dest dir, including sub-directories.
    """
    for item in os.listdir(src):
        file_path = os.path.join(src, item)

        # if item is a file, copy it
        if os.path.isfile(file_path):
            shutil.copy(file_path, dest)

        # else if item is a folder, recurse 
        Elif os.path.isdir(file_path):
            new_dest = os.path.join(dest, item)
            os.mkdir(new_dest)
            recursive_copy(file_path, new_dest)

編集:可能であれば、必ずshutil.copytree(src, dest)を使用してください。ただし、この場合、宛先フォルダーがまだ存在していないことが必要です。ファイルを既存のフォルダーにコピーする必要がある場合、上記の方法はうまくいきます!

1
Dustin Michels