I want to write a little script for managing a bunch of files I got. Those files have complex and different name but they all contain a number somewhere in their name. I want to take that number, place it in front of the file name so they can be listed logically in my filesystem.
I got a list of all those files using os.listdir but I’m struggling to find a way to locate the numbers in those files. I’ve checked regular expression but I’m unsure if it’s the right way to do this!
example:
import os
files = os.litdir(c:\\folder)
files
['xyz3.txt' , '2xyz.txt', 'x1yz.txt']`
So basically, what I ultimately want is:
1xyz.txt
2xyz.txt
3xyz.txt
where I am stuck so far is to find those numbers (1,2,3) in the list files
This (untested) snippet should show the regexp approach. The
searchmethod of compiled patterns is used to look for the number. If found, the number is moved to the front of the file name.If this code is used in production and not as homework assignment, a useful improvement would be to parse
match.group(0)as an integer and format it to include a number of leading zeros. That wayfoo2.txtwould become02foo.txtand get sorted before12bar.txt. Implementing this is left as an exercise to the reader.