Finding correct path to files in subfolders with os.walk with python?
<p>I am trying to create a program that copies files with certain file extension to the given folder. When files are located in subfolders instead of the root folder the program fails to get correct path. In its current state the program works perfectly for the files in the root folder, but it crashes when it finds matching items in subfolders. The program tries to use rootfolder as directory instead of the correct subfolder.</p>

<p>My code is as follows</p>

<pre><code># Selective_copy.py walks through file tree and copies files with
# certain extension to give folder
import shutil
import os
import re

# Deciding the folders and extensions to be targeted
# TODO: user input instead of static values
extension = "zip"
source_folder = "/Users/viliheikkila/documents/kooditreeni/"
destination_folder = "/Users/viliheikkila/documents/test"

def Selective_copy(source_folder):
    # create regex to identify file extensions
    mo = re.compile(r"(\w+).(\w+)")  # Group(2) represents the file extension
    for dirpath, dirnames, filenames in os.walk(source_folder):
        for i in filenames:
            if mo.search(i).group(2) == extension:
                file_path = os.path.abspath(i)
                print("Copying from " + file_path + " to " + destination_folder)
                shutil.copy(file_path, destination_folder)

Selective_copy(source_folder)
</code></pre>

<p><code>dirpath</code> is one of the things provided by <code>walk</code> for a reason: it gives the path to the directory that the items in <code>files</code> is located in.  You can use that to determine the subfolder you should be using.</p>

python os.walk