Amy Rose
Amy Rose

Reputation: 95

Adding "." after numbers in filename python

I have a folder with some files. The filenames have the format 123.createtable.txt, 124createtable.txt. I want to remove any whitespace in the filenames and also add a "." after the number sequence if not already present. I'm a little stuck on how to do the latter part.

import os
path = os.getcwd()
filenames = os.listdir(path) # Returns a list of the files of the directory given by path
for filename in filenames: # For each of the files
    if "." not in filename:
        filename.append (".")
    os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(' ', ''))) # Remove whitespace from filename

Upvotes: 0

Views: 772

Answers (2)

caspillaga
caspillaga

Reputation: 563

This code is far from oprimal, but should do the trick:

import os
path = os.getcwd()
filenames = os.listdir(path) # Returns a list of the files of the directory given by path
for filename in filenames: # For each of the files
    newFilename = ""
    for i in range(len(filename)-1):
        if filename[i] in '0123456789' and filename[i+1] not in '0123456789.':
            newFilename = newFilename + filename[i] + '.'
        else:
            newFilename = newFilename + filename[i]
    newFilename = newFilename + filename[-1]
    newFilename = newFilename.replace(' ','')    
    os.rename(os.path.join(path, filename), os.path.join(path, newFilename))

Upvotes: 2

LycuiD
LycuiD

Reputation: 2575

use regex:

import re
pat = re.compile(r"(\d+)") # pattern for "digits" match

and then use the pattern to substitute it with "." after using re.sub:

for filename in filenames:
    if any(str(x) in filename for x in list(range(10))):
        newname = re.sub(pat, "\\1.", filename)  # sub numbers
        newname = re.sub(" ", "", newname)       # sub whitespaces
    os.rename(filename, newname)

Upvotes: 0

Related Questions