Copying a directory tree with globbed files

(0 comments)

To copy a directory tree with only the files matching a globbed *Unix style pathname pattern) expression:

import os
import shutil
import glob

# Get all JSON files within and under the current directory.
json_files = glob.glob('./**/*.json', recursive=True)
DEST_ROOT = "/home/christian/"
for json_file in json_files:
    # Strip off initial "./".
dest_path = os.path.join(DEST_ROOT, json_file[1:][2:])
    # Make any directories that don't already exist.
dest_path = os.path.split(dest_path)[0]
os.makedirs(dest_path, exist_ok=True)
    # Copy the file.
shutil.copy(json_file, dest_path)
Currently unrated

Comments

Comments are pre-moderated. Please be patient and your comment will appear soon.

There are currently no comments

New Comment

required

required (not published)

optional

required