python

How to move a file or directory in Python

In this tutorial, we are going to see different ways to move files and directories in Python.
 

How to move a file or directory in Python

To move a file in Python, we need to import the “os” and “shutil” modules that allow us to move files in Python. These two modules provide methods to do so, the “shutil” module has more practical methods than “os”.

import shutil, os

# Move a file from dir1 to dir2
shutil.move('/Users/wtlx/dir1/file.txt', '/Users/wtlx/dir2/file.txt')

# Move a file by renaming its path
os.rename('/Users/wtlx/dir1/file.txt', '/Users/wtlx/dir2/file.txt')
Remember the destination directory must exist.

 

 

Example to move several files at the same time
import shutil, os

files = ['file1.txt', 'file2.txt', 'file3.txt', 'file4.txt']

for file in files:
    shutil.move(file, 'destination_directory')

 

Move a directory to another directory

We can also move a complete directory to another location, for example.

src = 'Path_to_source_directory'
dest =  'Path_to_destination_directory'

shutil.move(src, dest)

Some important points:

  • If the destination directory exists, the source directory will be moved into it.
  • If the destination directory does not exist, it will be created.
  • If the path is not valid, an error may occur.
  • If the destination directory already contains another directory with the same name as the source directory, this will cause an error.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *