简体   繁体   中英

Copying recursively in python3

i have to get my fingers more on python, i didn't do much in python, so i don't really know how to start with this task.

I've already read some questions here on stack overflow, watched some yt-videos and also googled a ton, but i don't think, that there was one question similar to my task.

Lets say my directory looks like this:

The main folder is called "Test", it got 2 directories in it: 1 & 2.

Folder 1 also contains Folder 11, in which my file i have to copy is stored.

After going through these directories, it should go back to start"Test", opening Folder 2, no files are there, so its goes deeper into Folder 22, there are also no files, so it goes deeper again into Folder 23, where the last file is and it should copy this, to my destination folder.

Unfortunately i can't display my directories correctly, the List-formatting of stack overflow doesn't work for me idk.

I am working on Linux/Mac and python3 is used.

code

#recursive copy method
import os
import shutil, errno

root_src_dir = '/Users/yolomir/OneDrive/OneDrive - ****'
root_dst_dir = '/Users/yolomir/OneDrive/OneDrive - ****'

for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exist(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exist(dst_file):
            os.remove(dst_file)
        shutil.copy(src_file, dst_dir)

i solved it by myself and for all of you, that ever need a script, which checks your directories recursively and copy all files of a specific kind:

from os import path
import shutil
import os
 
path = r"your/start/directory"
destination = r"your/destination/directory" 
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.yourfileextension' in file:
            files.append(os.path.join(r, file))
 
for file in files:
       if os.path.isfile(file):
           shutil.copy2(file, destination)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM