How to move files in Python

Because the filesystem sees renaming and moving files as being the same thing you can do it in two ways that achieve the same result:

  • Use shutil.move()
  • use os.rename()

Using shutil.move()

>>> import shutil
>>> shutil.move('file1.txt', 'MoveHere')
'MoveHere/file1.txt'

When using the move() function, a copying function is used to copy the file to the destination and then the source is removed.

moving files in Python

Using os.rename()

The rename() function is used if the files are on the same file system.

>>> import os
>>> os.rename('file1.txt', 'MoveHere/file1.txt')

Note:
You achieve the same result in both cases.
In the case of os.rename() you have to add full path to the destination folder (including the name of the file) … at least in Windows 10.
Be aware that things behave differently on Linux than on Windows.

Leave a Reply