Open In App

Python – Move all files from subfolders to main folder

This article will discuss how to move all files from the subfolder to the main folder using Python. The approach is simple it is similar to moving files from one folder to another using Python, except here the main folder or parent folder of the subfolder is passed as the destination.

Modules Used

Functions Used

Syntax: os.path.join(path, *paths) 
Parameter: 
path: A path-like object representing a file system path. 
*path: A path-like object representing a file system path. It represents the path components to be joined. 
A path-like object is either a string or bytes object representing a path.
Note: The special syntax *args (here *paths) in function definitions in python is used to pass a variable number of arguments to a function. 
Return Type: This method returns a string which represents the concatenated path components. 

Syntax: os.listdir(path)
Parameters: 
path (optional) : path of the directory
Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list.



Syntax: shutil.move(source, destination, copy_function = copy2)

Parameters:
source: A string representing the path of the source file.
destination: A string representing the path of the destination directory.
copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy, copytree, etc for this parameter.

Return Value: This method returns a string which represents the path of newly created file.

For moving files from the sub-folder to main folder we first have to import the required packages and then specify the paths of the source and destination directory. As the destination directory, remember to pass the destination of the main folder. Now add provisions to recursively move files from source to destination.

Source folder(subfolder):



src_folder 

Destination folder(main folder):

destination_folder before Compiling

Program :




import shutil
import os
  
# Define the source and destination path
source = "Desktop/content/waste/"
destination = "Desktop/content/"
  
# code to move the files from sub-folder to main folder.
files = os.listdir(source)
for file in files:
    file_name = os.path.join(source, file)
    shutil.move(file_name, destination)
print("Files Moved")

Output:

Files Moved

destination_folder after Compiling

output.gif

Article Tags :