Amy Rose Amy Rose - 15 days ago 6
Python Question

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

Answer

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))