-4

I have this complicated nested structure of directories, and I want to get rid of the directories and only keep all my files in a single directory. How can I do this in Python?

Thank you!

j. doe
  • 23
  • 2
  • 5

1 Answers1

0

This example below moves all the files in the directories and sub directories to a different directory. This is completed by using the 'os' and 'shutil' operations to list and move files within directories.

import shutil
import os
from os import walk


#the directory where you're trying to extract files from
directory_path = "example"
#the output directory (where you're wanting to store the files)
output_dir = "output2"

#if the output directory doesn't exist
if not os.path.exists(output_dir):
    #produce an output directory
    os.makedirs(output_dir)

#if the input directory doesn't exist
if not os.path.exists(directory_path):
    #throw a warning
    print("The directory you have selected doesn't exist")
    #exit
    exit()

#define a list of directories
file_list = [] 

#walk allows you to obtain a list of files and directories within a selected path
#for directories and files in walk(directory_path)
for (directory, directory_names, filenames) in walk(directory_path):
    #filenames is a list, therefore, we must add the directory to every file in the list
    for files in filenames:
        #add the directory path to the filename
        path = directory + "/" + files
        #append it to the list
        file_list.append(path)


#for every filepath in the list
for filepath in file_list:
    #use shutil to move the file to the output_directory
    shutil.move(filepath, output_dir)

Here's a shortened example that completes the same goal:

import shutil
import os
from os import walk

directory_path = "example"
output_dir = "output2"

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

if not os.path.exists(directory_path):
    print("The directory you have selected doesn't exist")
    exit()

for (directory, directory_names, filenames) in walk(directory_path):
    for files in filenames:
        path = directory + "/" + files
        shutil.move(path, output_dir)