Movatterモバイル変換


[0]ホーム

URL:


Open In App

Prerequisite:OS module in Python
In Python3,rename() method is used to rename a file or directory. This method is a part of theos module and comes in 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 givenn 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 therename() andlistdir() methods in the os module.
 

Thelistdirmethod lists out all the content of a given directory.


Syntax for listdir() : 

list = os.listdir('src') : where src is the source folder 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. 

The accepted format for destination (dst) and source (src) addresses to be given as arguments inos.rename(src,dst)is"folder_name/file_name".
  
Below is the implementation : 

Python3
# Python 3 code to rename multiple# files in a directory or folder# importing os moduleimportos# Function to rename multiple filesdefmain():folder="xyz"forcount,filenameinenumerate(os.listdir(folder)):dst=f"Hostel{str(count)}.jpg"src=f"{folder}/{filename}"# foldername/filename, if .py file is outside folderdst=f"{folder}/{dst}"# rename() function will# rename all the filesos.rename(src,dst)# Driver Codeif__name__=='__main__':# Calling main() functionmain()

Output :
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 program to rename multiple files
Improve
Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp