- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Rename multiple files using Python
To rename files in Python, use the rename() method of the os module. The parameters of the rename() method are the source address (old name) and the destination address (new name).
Install and Import the OS module
To install the OS module −
pip install os
To import −
Rename multiple files using rename() method
The rename() method can be easily used to rename multiple files −
import os # Function to rename multiple files def main(): i = 0 path="E:/amit/" for filename in os.listdir(path): my_dest ="new" + str(i) + ".jpg" my_source =path + filename my_dest =path + my_dest # rename() function will # rename all the files os.rename(my_source, my_dest) i += 1 # Driver Code if __name__ == '__main__': # Calling main() function main()
The above will rename all the files in a folder “amit”.
Rename specific multiple files
In Python, you can select which multiple files in a folder are to be renamed.
import os filesRename = ['demo_1.txt', 'demo_2.txt', 'demo_3.txt',] folder = r"E:\docs\" # Iterate for file in os.listdir(folder): # Checking if the file is present in the list if file in filesRename: oldName = os.path.join(folder, file) n = os.path.splitext(file) b = n + '_new' + '.txt' newName = os.path.join(folder, b) # Rename the file os.rename(oldName, newName) res = os.listdir(folder) print(res)
The above will rename only 3 files in the docs folder.
- Rename multiple files using Java
- How to rename multiple files recursively using Python?
- How to rename multiple files in a directory in Python?
- How to merge multiple files into a new file using Python?
- How to spilt a binary file into multiple files using Python?
- Copy, Rename and Delete Files in Perl
- How to rename directory using Python?
- How to rename a file using Python?
- Python - Rename column names by index in a Pandas DataFrame without using rename()
- Python - Write multiple files data to master file
- Multiple .java files
- Using G++ to compile multiple .cpp and .h files
- How to share common data among multiple Python files?
- How we can split Python class into multiple files?
- Python - How to rename multiple column headers in a Pandas DataFrame with Dictionary?