-2

I have a Folder with many subfolders that also have subfolder in them and they also have subfolders and so on. I need certain files from that folder to be found by python and copied to a destination folder.

I found shutil.copy but this need the complete path to find the file.

How do i copy files with Python that are either in the folder or one of the subfolders or their subfolders... ?

Edit: I dont have the complete Path to the files, the files are somewhere in that folder structre, if i would have the complete path this wouldnt be a problem.

Erik
  • 49
  • 5
  • use `pathlib.Path.glob` with some filters and use copy on them ? – Kris Sep 26 '22 at 08:54
  • 1
    "...but this need the complete path". So, provide the complete path. What's the problem? –  Sep 26 '22 at 08:54
  • 1
    Check if your target directory is empty and then use loop if not. Use recursion. – Mateusz Sep 26 '22 at 08:55
  • @SembeiNorimaki the problem is that i dont know the complete Path. Thats why i need it to search through. The FIles are somewhere in this giant folder structure – Erik Sep 26 '22 at 09:03
  • @MateuszStyrna here is the problem that i dont know how deep the folders go and that not every searched file has to exist somewhere in the structure – Erik Sep 26 '22 at 09:08

2 Answers2

0

Before copy using shutil.copy, get absolute path of all files

import os

def absoluteFilePaths(directory):
    for dirpath,_,filenames in os.walk(directory):
        for f in filenames:
            yield os.path.abspath(os.path.join(dirpath, f))

Get absolute paths of all files in a directory

Rabindra Nath Nandi
  • 1,433
  • 1
  • 15
  • 28
  • Here is the Problem again that i dont know the complete Path the files are somewhere in this big folder structure. Meaning i dont have a source path – Erik Sep 26 '22 at 09:04
0

Here is what I found: https://www.geeksforgeeks.org/python-shutil-copytree-method/

The solutions seems to be shutil.copytree()

# Python program to explain shutil.copytree() method 
       
# importing os module 
import os 
   
# importing shutil module 
import shutil 
   
# path 
path = 'C:/Users / Rajnish / Desktop / GeeksforGeeks'
   
# List files and directories 
# in 'C:/Users / Rajnish / Desktop / GeeksforGeeks' 
print("Before copying file:") 
print(os.listdir(path)) 
   
   
# Source path 
src = 'C:/Users / Rajnish / Desktop / GeeksforGeeks / source'
   
# Destination path 
dest = 'C:/Users / Rajnish / Desktop / GeeksforGeeks / destination'
   
# Copy the content of 
# source to destination 
destination = shutil.copytree(src, dest) 
   
# List files and directories 
# in "C:/Users / Rajnish / Desktop / GeeksforGeeks" 
print("After copying file:") 
print(os.listdir(path)) 
   
# Print path of newly 
# created file 
print("Destination path:", destination)
Mateusz
  • 175
  • 9
  • This copies the complete folder tree, i only need some files that are somewhere in that tree – Erik Sep 26 '22 at 09:06