rename a file in python

To rename a file in Python, we can use the os or shutil modules. Here's an example using os.rename():

main.py
import os

# path to file to be renamed
old_name = '/path/to/old/file.txt'

# new name for the file
new_name = '/path/to/new/file.txt'

# rename the file
os.rename(old_name, new_name)
184 chars
11 lines

Alternatively, we can use shutil.move() to accomplish the same thing:

main.py
import shutil

# path to file to be renamed
old_name = '/path/to/old/file.txt'

# new name for the file
new_name = '/path/to/new/file.txt'

# rename the file
shutil.move(old_name, new_name)
190 chars
11 lines

Both methods work similarly, but shutil.move() has additional capabilities such as copying files to a different location while renaming.

related categories

gistlibby LogSnag