0

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
2
  • 1
    Use a regular expression to match the number, and replace it with the matched value and a . Commented Nov 21, 2016 at 17:50
  • 2
    Your indentation is wrong. The if statement should be indented 4 more spaces. Commented Nov 21, 2016 at 17:50

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.