Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

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. In this article, we will go through different methods of moving a file from one folder to another using Python.

Using the OS Module

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

Using shutil.move() method

Following is an example which shows how 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)

When we execute the above program, the defined file will be moved to the defined directory.

Using os.rename() method

The rename() method of os module in Python is used to relocate files from one location to another. By changing the directory name of the files, we can move the files using this function.

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))

When we execute the above program, the defined file will be moved to the defined directory.

Note? A file or directory name can be changed using either os.replace() or os.rename().

When working on 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-oriented programming that is 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 the 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)

When we execute the files present in the 'Works' folder moved to the 'Work TP' folder.

Updated on: 2025-05-15T18:20:01+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements