Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (11.4k points)

I looked into the Python os interface, but was unable to locate a method to move a file. How would I do the equivalent of $ mv ... in Python?

>>> source_files = '/PATH/TO/FOLDER/*' 

>>> destination_folder = 'PATH/TO/FOLDER' 

>>> # equivalent of $ mv source_files destination_folder

1 Answer

0 votes
by (106k points)
edited by
  • For moving file in Python, we have many methods some important one’s I am mentioning here:-

os.rename():-

We can move our file in Python using the os.rename() method. But you need to be aware that your source and destination file should be in the same disk.

import os

os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

shutil.move():-

We can also use shutil.move() method to move our file in Python. If your source and destination file are at the different disk in that case also this method works. If the destination file is on the current file system where the resource file is also present then shutil.move() uses os.rename()to move the file. Otherwise, shutil.move() copies the source file to the destination file using shutil.copy2() and then removes the source.

import shutil 

shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

  • Another thing we can do is we can use pathlib's classpath to move the file if the Python version is 3.4.

import pathlib

Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")

If you are looking for upskilling yourself in python you can join our Python Certification and learn from an industry expert. 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 27, 2019 in Python by Sammy (47.6k points)
+3 votes
2 answers

Browse Categories

...