I need to write a python script, so that giving a list of document names, it finds them in subfolders of a path, copy them and paste them in another folder.
The problem is that I need the program to also analyze subfolders, as the documents I need are 3 levels below the parent folder.
I have a list of the document names, and would need the script to:
Example:
1. List with the document names needed:
documents_to_move = ["49684.32_PJ-R2106027AROJ 1.jpg", "51010.32_PJ-R2206073AZJ 1.jpg"]
2. Pass a function so that does what needed:
function(documents_to_move, "\192.168.0.222\Renatta\Renatta 2022\02. WEB\01. WEB FOTOS\02. SUBIDO A WEB")
3. The function would have to localize these files along the subfolders of the mother folder:
49684.32_PJ-R2106027AROJ 1.jpg --> \192.168.0.222\Renatta\Renatta 2022\02. WEB\01. WEB FOTOS\02. SUBIDO A WEB\10. Octubre\2022-10-07_Carlota\BAJA
51010.32_PJ-R2206073AZJ 1.jpg --> \192.168.0.222\Renatta\Renatta 2022\02. WEB\01. WEB FOTOS\02. SUBIDO A WEB\01. Enero\2022-01-22_Gala&Marta\BAJA
4. Copy these files, and paste them in a folder in my desktop: "C:\Users\Pablo\Desktop\Pablo"
I have tryied these scripts:
def find_all(name, path):
result = []
for root, dirs, files in os.walk(path):
if name in files:
result.append(os.path.join(root, name))
return result
and also:
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
But both return me an empty list, even if I try with a document which is inside of that path.
Thanks in advance for your help.
Pablo
First find your file in the source folder, could be in the main or any subdirectory. It will check if the file is on your list.
Then, if it's on your list, it will print the location of the file and move it.
import os
import shutil
def move_function(filestomove, source_input, destination_input):
fileList = filestomove
source = source_input
destination = destination_input
for root, dirs, files in os.walk(source):
for file in files: # loops through directories and files
if file in fileList: # compares to your list
print(os.path.join(source, file))
src_path = os.path.join(source, file)
dst_path = os.path.join(destination, file)
shutil.copy(src_path , dst_path)
Now to run it all you have to do is,
documents_to_move = ["49684.32_PJ-R2106027AROJ 1.jpg", "51010.32_PJ-R2206073AZJ 1.jpg"]
source = r'C:\Users\Pablo\Documents\source'
destination = r'C:\Users\Pablo\Desktop\Pablo'
move_function(documents_to_move, source, destination)