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.