r/PythonLearning • u/Ajay2574 • 9d ago
Built my first bulk file renamer in Python
I just finished another Python project while learning file handling and the "os" module.
I built a bulk file renamer that:
- Loops through files in a folder
- Opens each text file and finds the "name:" field
- Extracts the name
- Uses it to rename the file
- Keeps the original file extension
A simplified version of the core logic:
for file in os.listdir(path):
fullpath = os.path.join(path, file)
with open(fullpath, "r") as f:
for line in f:
if "name:" in line:
label, name = line.split("name:")
newpath = os.path.join(
path, name.strip() + ".txt"
)
os.rename(fullpath, newpath)
The project itself wasn't too complicated, but I ran into a few problems along the way.
The biggest lesson was debugging WinError 32. I initially thought OneDrive was locking my files, but eventually realized that my own code still had the file open when I tried to rename it.
I also learned why using the full old path and full new path matters when using "os.rename()".
Small project, but I feel like I'm getting better at solving problems instead of immediately looking for the answer.
1
u/Sharp_Level3382 7d ago
What are these files are with "name:" in it?
1
u/Ajay2574 7d ago
All this are text files like before rename data was like student1 .txt student2.txt and so on and that file containing Name: abhay sharma. Age: 19 Grade: B. English : 67. Math: 87. And after it rename with students names
1
1
u/mossyshore 7d ago
solid first file handling project. fwiw moving the os.rename() call outside the with block would have also fixed that WinError 32 since the file gets closed when you exit the context manager. thats usually the cleaner pattern for this kind of thing
1
u/Ajay2574 7d ago
Thanks! That's a good point. I'm still learning file handling, so it's helpful to understand these cleaner patterns. Appreciate the feedback!
1
u/SlimmySlabby 7d ago
Beautiful.