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 - How to Check if a file or directory exists
Next article icon

Python | Move or Copy Files and Directories

Last Updated : 29 Dec, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Let’s say we want to copy or move files and directories around, but don’t want to do it by calling out to shell commands. The shutil module has portable implementations of functions for copying files and directories.

Code #1 : Using shutil module




import shutil
  
# Copy src to dst. (cp src dst)
shutil.copy(src, dst)
  
# Copy files, but preserve metadata (cp -p src dst)
shutil.copy2(src, dst)
  
# Copy directory tree (cp -R src dst)
shutil.copytree(src, dst)
  
# Move src to dst (mv src dst)
shutil.move(src, dst)
 
 

The arguments to these functions are all strings supplying file or directory names. The underlying semantics tries to emulate that of similar Unix commands, as shown in the comments. By default, symbolic links are followed by these commands. For example, if the source file is a symbolic link, then the destination file will be a copy of the file the link points to.

To copy the symbolic link instead, supply the follow_symlinks keyword argument as shown in the code below:

Code #2 :




shutil.copy2(src, dst, follow_symlinks = False)
  
# To preserve symbolic links in copied directories
shutil.copytree(src, dst, symlinks = True)
 
 

The copytree() optionally allows to ignore certain files and directories during the copy process. To do this, supply an ignore function that takes a directory name and filename listing as input, and returns a list of names to ignore as a result. The example is shown in the code below –

Code #3 :




def ignore_pyc_files(dirname, filenames):
    return [name in filenames if name.endswith('.pyc')]
  
shutil.copytree(src, dst, ignore = ignore_pyc_files)
 
 

Since ignoring filename patterns is common, a utility function ignore_patterns() has already been provided to do it as shown in the code given below.

Code #4 :




shutil.copytree(src, dst, ignore = shutil.ignore_patterns('*~', '*.pyc'))
 
 

How it works?

  • Using shutil to copy files and directories is mostly straightforward.
  • However, one caution concerning file metadata is that functions such as copy2() only make the best effort in preserving this data.
  • Basic information, such as access times, creation times, and permissions, will always be preserved, but the preservation of owners, ACLs, resource forks, and other extended file metadata may or may not work depending on the underlying operating system and the user’s own access permissions.
  • The user probably wouldn’t want to use a function like shutil.copytree() to perform system backups.

When working with filenames, make sure to use the functions in os.path for the greatest portability (especially if working with both Unix and Windows).

Code #5 : Example




filename = '/Users/gfg/programs/abc.py'
  
import os.path
os.path.basename(filename)
 
 
'abc.py'

 




os.path.dirname(filename)
 
 
'/Users/gfg/programs'

 




os.path.split(filename)
 
 
('/Users/gfg/programs', 'abc.py')

 




os.path.join('/new/dir', os.path.basename(filename))
 
 
'/new/dir/spam.py'

 




os.path.expanduser('~/gfg/programs/spam.py')
 
 
'/Users/gfg/programs/abc.py'

One tricky bit about copying directories with copytree() is the handling of errors. For example, in the process of copying, the function might encounter broken symbolic links, files that can’t be accessed due to permission problems, and so on.



Next Article
Python - How to Check if a file or directory exists

M

manikachandna97
Improve
Article Tags :
  • Python
  • Python file-handling-programs
  • Python os-module-programs
  • python-file-handling
  • python-os-module
Practice Tags :
  • python

Similar Reads

  • Listing out directories and files in Python
    The following is a list of some of the important methods/functions in Python with descriptions that you should know to understand this article. len() - It is used to count number of elements(items/characters) of iterables like list, tuple, string, dictionary etc. str() - It is used to transform data
    6 min read
  • Python - How to Check if a file or directory exists
    Sometimes it's necessary to verify whether a dictionary or file exists. This is because you might want to make sure the file is available before loading it, or you might want to prevent overwriting an already-existing file. In this tutorial, we will cover an important concept of file handling in Pyt
    5 min read
  • Python - List Files in a Directory
    Sometimes, while working with files in Python, a problem arises with how to get all files in a directory. In this article, we will cover different methods of how to list all file names in a directory in Python. Table of Content What is a Directory in Python?How to List Files in a Directory in Python
    9 min read
  • Python - Move and overwrite files and folders
    In this article, we will be learning on moving a collection of files and folders where there may be files/folders with the same name as in the source name in the destination. So that we may need to overwrite the existing destination file with the source file. The shutil.move() method is used to move
    3 min read
  • Copy all files from one directory to another using Python
    Copying files from one directory to another involves creating duplicates of files and transferring them from one folder to another. This is helpful when organizing files, backing them up, or moving them to different locations on your computer. Let’s explore various methods to do this efficiently. Us
    2 min read
  • Python - Move Files To Creation and Modification Date Named Directories
    We all understand how crucial it is to manage files based on their creation and modification dates. So, in this article, we will try to build a Python script that would move all of your files to new directories based on their creation and modification dates. Basically, it will look for directories a
    4 min read
  • Create temporary files and directories using tempfile
    Python tempfile module allows you to create a temporary file and perform various operations on it. Temporary files may be required when we need to store data temporarily during the program's execution or when we are working with a large amount of data. These files are created with unique names and s
    5 min read
  • Python | os.DirEntry.is_file() 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.scandir() method of os module yields os.DirEntry objects corresponding to the
    3 min read
  • Python - Copy Directory Structure Without Files
    In this article, we will discuss how to copy the directory structure with files using Python. For example, consider this directory tree: We have a folder named "base" and inside have we have one folder named "Structure". "Structure" has some folders inside which also contain some files. Now we have
    3 min read
  • Python | os.DirEntry.is_dir() 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.scandir() method of os module yields os.DirEntry objects corresponding to the
    3 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