Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | os.renames() method
Next article icon

Copy Files and Rename in Python

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Copying and renaming files is a common task in programming, and Python provides several ways to accomplish this efficiently. In this article, we will explore some commonly used methods for copying files and renaming them: using the shutil module's copy() and pathlib module's Path class. Each method has its advantages, and choosing the right one depends on the specific requirements of your project.

How To Copy Files And Rename Them In Python?

Below, are the generally used method for How To Copy Files And Rename Them In Python.

  • Using shutil.copy()
  • Using pathlib.Path

Copy Files And Rename using shutil.copy()

The shutil module in Python is a powerful utility for file operations, including copying files. The copy() function from this module allows us to copy a file from one location to another. Here's a simple example: This example uses the shutil.copy() method to copy the file and shutil.move() to rename the copied file in the destination folder.

Python
import shutil  def copy_and_rename(src_path, dest_path, new_name): 	# Copy the file 	shutil.copy(src_path, dest_path)  	# Rename the copied file 	new_path = f"{dest_path}/{new_name}" 	shutil.move(f"{dest_path}/{src_path}", new_path)  # Example usage source_file = "example.txt" destination_folder = "destination_folder" new_file_name = "renamed_example.txt"  copy_and_rename(source_file, destination_folder, new_file_name) print("Successfully Created File and Rename") 

Output

Successfully Created File and Rename

Copy Files And Rename Using pathlib.Path

The pathlib module was introduced in Python 3.4 to provide an object-oriented interface for file system paths. The Path class includes the rename() method, making it convenient for both copying and renaming files: In this example, the Path class is used to create path objects, and rename() is employed to both copy and rename the file in the destination folder.

Python
from pathlib import Path  def copy_and_rename_pathlib(src_path, dest_path, new_name): 	# Create Path objects 	src_path = Path(src_path) 	dest_path = Path(dest_path)  	# Copy and rename the file 	new_path = dest_path / new_name 	src_path.rename(new_path)  # Example usage source_file = "example.txt" destination_folder = "destination_folder" new_file_name = "renamed_example.txt"  copy_and_rename_pathlib(source_file, destination_folder, new_file_name) print("Successfully Created File and Rename") 

Output :

Successfully Created File and Rename

Next Article
Python | os.renames() method

T

tritik448
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • python-os-module
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

  • Copy And Replace Files in Python
    In Python, copying and replacing files is a common task facilitated by modules like `shutil` and `os`. This process involves copying a source file to a destination location while potentially replacing any existing file with the same name. Leveraging functions like `shutil.copy2` and `os.remove`, thi
    2 min read
  • How to copy file in Python3?
    Prerequisites: Shutil When we require a backup of data, we usually make a copy of that file. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Here we will learn how to copy a file using Pyt
    2 min read
  • Python | os.rename() method
    OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality. To rename a file or directory in Python you can use os.rename() function of OS mo
    2 min read
  • Automate Renaming and Organizing Files with Python
    In this article, we are going to know how to automate renaming and organizing  files with Python, hence, the article is divided into two sections: one teaches us how to organize files and the latter how to rename files. Here we will learn about how to rename and organize files in Python. We will use
    5 min read
  • Python | os.renames() method
    OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.renames() method is a recursive directory or file renaming function. It works
    2 min read
  • Array Copying in Python
    In Python, there are several ways to copy arrays, each with different behaviors. The three main methods for copying arrays are: Simply using the assignment operator.Shallow CopyDeep Copy1. Assigning the ArrayWe can create a copy of an array by using the assignment operator (=). However, this does no
    4 min read
  • Python - Swap commas and dots in a String
    In this article, we'll explore how to swap commas and dots in a string in Python. Using str.translate() str.translate() that allows for character substitution within a string using a translation table. It enables quick transformations, such as swapping characters like commas and dots. Example: [GFGT
    2 min read
  • Python | Pandas Dataframe.rename()
    Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas rename() method is used to rename any index, column or row. Renaming of column
    3 min read
  • Python | Pandas Series.rename()
    Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.rename() function is used to
    2 min read
  • Python MongoDB- rename()
    MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. Refer to MongoDB and Python for an in-depth introduction to the topic. N
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences