How do you rename a file in python


You can rename a file in Python using the os. rename() method. This method accepts two arguments: the old filename and the new filename. If you’re using a version of Python before 3.3, you can use the shuttle.move() function instead.

The os.rename() Method

The os. rename() method renames the file or directory src to DST.src, and DST should be strings. If either src or DST is a non-absolute path, then the path will be interpreted as relative to the current working directory. On Windows, if dst already exists, OSError will be raised even if os. rename() succeeds.

The rename() function returns a tuple consisting of the renamed and destination filename.

If you want to rename a file in Python, you can do so using the os.rename() method. This method is a part of the os module and comes built into Python. To use it, you must first import the os module into your script:

import os
os.rename(“source_file”, “destination_file”)
In this example, we’re renaming a file called “source_file” to “destination_file.” We can also specify a different path for the destination file:

os.rename(“source_file”, “/home/destination_file”)
If you want to rename multiple files at once, you can use the glob module:

import glob
files = glob.glob(“*.txt”)
for file in files:
os.rename(file, file[:-4] + “.jpg”)

The shutil.move() Method

The shutil.move() method will first try to rename the file; if that fails, it will try to copy the file and then delete the original (if the copy was successful). This is useful if you want to script moving files between different locations:

import shutil

shutil.move(“path/to/fileA”, “path/to/fileB”)


There are two ways to rename files in Python. One way is to use the os module and its rename function. Another way is to use the shutil module and its rename function.

Leave a Reply

Your email address will not be published.