'Rename multiple files in multiple sub folders using python
Beginer python coder here.
I've been struggling with this problem for few days now and finally given up and seeking help.
Problem illustrated:
All Student folders:
Student a:
Work.pdf
Work2.pdf
Student b:
Work.pdf
Work2.pdf
Folders Student a and student b, contain two files each.
I need to rename those files as homework1.pdf and homework2.pdf
Ofcourse in real life I have more than 2 folders.
I thought a for loop using os.rename() would work but I can't get it to change multiple files.
Here's what I tried
import os
# assign directory
directory = 'all Student folders'
# iterate over files
for root, dirs, files in os.walk(directory):
for filename in files:
if filename =='work.pdf':
os.rename('work.pdf', homework1.pdf')
Many thanks...
Solution 1:[1]
You need to use the file in the dir where it is.
import os
# assign directory
directory = "all Student folders"
# iterate over files
for root, _, files in os.walk(directory):
for file_name in files:
if file_name == "Work.pdf":
os.rename(f"{root}/{file_name}", f"{root}/homework1.pdf")
else:
new_name = file_name.replace(f"Work", "homework")
os.rename(f"{root}/{file_name}", f"{root}/{new_name}")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Floh |
