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 the os.rename, os.replace or shutil.move methods.

They both take the source and destination path strings as arguments respectively.

For instance, we write:

import os

os.rename("./foo.txt", "./bar.txt")

to move the file from ./foo.txt to ./bar.txt.

Likewise, we write:

import os

os.replace("./foo.txt", "./bar.txt")

or

import shutil

shutil.move("./foo.txt", "./bar.txt")

to do the same thing.

Conclusion

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

They both take the source and destination path strings as arguments respectively.

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 *