Change language

Python | Move or copy files and directories

| |

Code # 1: Using the shutil module

import shutil

 
# Copy src to dst. (srcst dst)
shutil.copy (src, dst)

 
# Copy files but keep 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 that provide file or directory names. The basic semantics tries to emulate the semantics 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 that the link points to.

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

Code # 2:

shutil. copy2 (src, dst, follow_symlinks = False )

 
# Save symlinks in copied directories

shutil.copytree (src, dst, symlinks = True )

copytree () additionally allows you to ignore copy specific files and directories during the copying process. To do this, provide an ignore function that takes a directory name and a list of filenames as input and returns a list of names to ignore. An 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 it is common to ignore filename patterns, there is already a ignore_patterns () utility function provided for this as a show but in the code below.

Code # 4:

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

How does it work?

  • Usage shutil for copying files and directories is mostly straightforward.
  • However, one caveat regarding file metadata is that functions like copy2 (), make every effort to preserve this data.
  • Basic information such as access times, creation times and permissions will always be preserved, but retaining owners, ACLs, resource forks, and other extended metadata These files may or may not work depending on the underlying operating system and its own user. access permissions.
  • The user probably won’t want to use a function like shutil.copytree (), to perform a system backup.

When working with filenames, be sure to use the functions from os.path for maximum portability (especially when 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 of the copytree () when copying directories using copytree () is error handling. For example, during the copy process, the function may detect broken symlinks, files that cannot be accessed due to permission issues, etc.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically