user1842999
user1842999

Reputation: 13

Python: rename all files in a folder using numbers that file contain

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

Upvotes: 0

Views: 1490

Answers (2)

user4815162342
user4815162342

Reputation: 154911

This (untested) snippet should show the regexp approach. The search method of compiled patterns is used to look for the number. If found, the number is moved to the front of the file name.

import os, re

NUM_RE = re.compile(r'\d+')

for name in os.listdir('.'):
    match = NUM_RE.search(name)
    if match is None or match.start() == 0:
        continue  # no number or number already at start
    newname = match.group(0) + name[:match.start()] + name[match.end():]
    print 'renaming', name, 'to', newname
    #os.rename(name, newname)

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 way foo2.txt would become 02foo.txt and get sorted before 12bar.txt. Implementing this is left as an exercise to the reader.

Upvotes: 2

inspectorG4dget
inspectorG4dget

Reputation: 113945

Assuming that the numbers in your file names are integers (untested code):

def rename(dirpath, filename):
    inds = [i for i,char in filename if char in '1234567890']
    ints = filename[min(inds):max(inds)+1]
    newname = ints + filename[:min(inds)] + filename[max(inds)+1:]
    os.rename(os.path.join(dirpath, filename), os.path.join(dirpath, newname))

def renameFilesInDir(dirpath):
    """ Apply your renaming scheme to all files in the directory specified by dirpath """

    dirpath, dirnames, filenames = os.walk(dirpath):
    for filename in filenames:
        rename(dirpath, filename)
    for dirname in dirnames:
        renameFilesInDir(os.path.join(dirpath, dirname))

Hope this helps

Upvotes: 0

Related Questions