Python Forum

Full Version: changing characters in multiple strings in a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Well I've tried many things and I can't seem to find a way to change strings or file names in a list such as:

CT-0921-0001
CT-0921-0002
CT-0922-0003
.
.
.

TO new file names

CT-008-0001
CT-008-0002
CT-008-0003
.
.
.

Any help is greatly appreciated. Thanks ahead of time
>>> "CT-0921-0001".replace('921', '08')
'CT-008-0001'
Below code will work well for whatever in between "-"
#!/usr/bin/python
import glob
from __future__ import print_function

for fileName in glob.glob('CT-*'):
        fileName = fileName.split('-')
        fileName[1] = '008'
        fileName = '-'.join(fileName)
        print(fileName)
Thank you. I was looking at glob function. It printed the new names very nicely but I actually need the names in the directory to be changed. So I am looking at os.rename(fileName, fileName.replace ...). Not sure how to make it change the names in the directory.