简体   繁体   中英

Python look for specific file in all subdirectories and copy it to another directory/

I have a folder in C:/Print with thousands of directories. They are named with numbers. Each directory contains subdirectories that may be named differently.

I want to input a number, then the program has to go into the directory that is named like the input and check ALL subdirectoriesfor the file that is named just like this input but with.tif extension and then copy it to another directory.

Example:

Input "63783"

C:/Print/63783/FCB/63783.tif -> copy it to D:/HotFolder

Can I please get some help?

I'd love to help you out but I think we're gonna need a little more information, is there a Discord account or server that I can contact you at? Try this code, see if it works:

import os, shutil

number = int(input("Etner number: "))

path = "C:\\Print\\" + str(number)
os.chdir(path)
destination = "D:\\HotFolder"
path_list = os.listdir()

for sub_dir in path_list:
    sub_path  = path+ "\\" +sub_dir
    os.chdir(sub_path)
    files = os.listdir()
    if str(number) + ".tif" in  files:
        source = sub_path + "\\" + str(number) + ".tif"
        shutil.move(source, destination)
def f_name(some_input):
    import os, shutil

    src_path = "src_dir_path"
    src_path = os.path.join(src_path, some_input)  # dir path to look for
    dst_path = "dst_dir_path"

    if not os.path.isdir(src_path):  # no directory named <some_input>
        return  

    if not os.path.isdir(dst_path):  # destination folder check
        os.mkdir(dst_path)  

    copy_targets = [(root, filename) for root, _, filenames in os.walk(src_path) for filename in filenames if filename.endswith(".tif")]

    for root, filename in copy_targets:
        origin = os.path.join(root, filename)
        dest = os.path.join(dst_path, filename)
        shutil.copyfile(origin, dest)  # copy file

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