How to move a file from one folder to another using Python?


The Python shutil module provides a number of functions for high-level operations on individual files and file collections.

We could move a file from one folder to another. You can accomplish this in a number of ways.

Using OS Module

The Python OS module gives users the ability to create interactions with their operating systems.

The shutil.move() method can be used to move files. To move a file from one directory to another, follow the instructions below.

Example - Using shutil.move() method

Following is an example to move a file from one folder to another using shutil.move() method −

# importing the modules import shutil import os # Providing the folder path origin = 'C:\Users\Lenovo\Downloads\Works\' target = 'C:\Users\Lenovo\Downloads\Work TP\' # Fetching the list of all the files files = os.listdir(origin) # Fetching all the files to directory for f in files: shutil.move(origin + f, target)

Output

As an output, we can see that the files present in the ‘Works’ folder moved to the ‘Work TP’ folder.

Example - Using os.rename() method

The rename() module, which is used to relocate files from one location to another, is one of this module's functions. By changing the directory name of the files, this function moves the files.

Following is an example to move a file from one folder to another using os.rename() method −

import os origin = 'C:\Users\Lenovo\Downloads\Works\' target = 'C:\Users\Lenovo\Downloads\Work TP\' files = os.listdir(origin) for q in files: os.rename(origin + q, target + q))

Output

As an output, we can see that the files present in the ‘Works’ folder moved to the ‘Work TP’ folder.

Note − A file or directory name can be changed using either os.replace() or os.rename(). Depending on the operating system you're using, os.rename() presents problems in various ways.

When working on a software that requires compatibility with several operating systems, os.replace() may be a preferable option because it will report errors consistently across various systems.

Using Pathlib Module

A common module in Python for providing an object used to manage various files and dictionaries is called pathlib. Path is the name of the main object used to work with files.

Example

Following is an example to move a file from one folder to another using pathlib module −

from pathlib import Path import shutil import os origin = 'C:\Users\Lenovo\Downloads\Works\' target = 'C:\Users\Lenovo\Downloads\Work TP\' for f in Path(origin).glob('trial.py'): shutil.move(os.path.join(origin,f),target)

Output

As an output, we can see that the files present in the ‘Works’ folder moved to the ‘Work TP’ folder.

Updated on: 18-Aug-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements