Categories
Python Answers

How to move a file in Python?

Spread the love

Sometimes, we want to move a file in Python.

In this article, we’ll look at how to move a file in Python.

How to move a file in Python?

To move a file in Python, we can use os.rename, os.replace or shutil.move.

For instance, we write

import os
import shutil

os.rename("path/to/current/file.foo", "path/to/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/destination/for/file.foo")

to call os.rename, os.replace, and shutil.move with the source and destination paths.

We move the file from the source path to the destination path with all 3 methods.

Conclusion

To move a file in Python, we can use os.rename, os.replace or shutil.move.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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