Prerequisite : OS module in Python
In Python3, rename() method is used to rename a file or directory. This method is a part of the os module and comes extremely handy.
Syntax for os.rename() :
os.rename(src, dst) : src is source address of file to be renamed and dst is destination with the new name.
Now say given n images in a folder having random names. For example, consider the image below:
Now the requirement is to rename them in ordered fashion like hostel1, hostel2, …and so on. Doing this manually would be a tedious task but this target can be achieved using the rename() and listdir() methods in os module.
The listdir method lists out all the content of a given directory.
Syntax for listdir() :
list = os.listdir(‘Src’) : Where Src is the source to be listed out.
The following code will do the job for us. It traverses through the lists of all the images in xyz folder, defines the destination (dst) and source (src) addresses and renames using rename module.
Below is the implementation :
The output of this code will look something like this –
Note : This code may not run in online IDE, since it use external image file directory.
- Python | How to use Multiple kv files in kivy
- Python | Write multiple files data to master file
- Python | os.rename() method
- Python | Pandas TimedeltaIndex.rename
- Python | Pandas Dataframe.rename()
- Python | Pandas Series.rename()
- Rename all file names in your directory using Python
- Working with zip files in Python
- Reading CSV files in Python
- Working with PDF files in Python
- Working with csv files in Python
- Interact with files in Python
- Upload files in Python
- HDF5 files in Python
- Downloading files from web using Python
- Writing CSV files in Python
- Reading and Writing CSV Files in Python
- Python | Reading .ini Configuration Files
- Writing files in background in Python
- Python | Merge two text files
Improved By : ChristopherGarland