gyanender singh
gyanender singh

Reputation: 33

How to change file names by replacing characters?

I've 6000 similar files and their names changed a bit and i don't understand how. So my files now look like this

HARPS.2010-10-19T02_24_55.819_e2ds_A.fits
HARPS.2016-01-20T00_38_12.300_e2ds_A.fits
HARPS.2015-11-26T04_30_27.879_e2ds_A.fits

So i want to replace the '_' with ':' but not at all places. So basically i want them to look like this:

HARPS.2010-10-19T02:24:55.819_e2ds_A.fits
HARPS.2016-01-20T00:38:12.300_e2ds_A.fits
HARPS.2015-11-26T04:30:27.879_e2ds_A.fits

How can i do that?

Upvotes: 1

Views: 107

Answers (4)

Ashraful Islam
Ashraful Islam

Reputation: 12830

Try regex T(\d+)_(\d+)_(\d+) replace with T\1:\2:\3

import re

regex = r"T(\d+)_(\d+)_(\d+)"
subst = r"T\1:\2:\3"

list_test = ["HARPS.2010-10-19T02_24_55.819_e2ds_A.fits",
             "HARPS.2016-01-20T00_38_12.300_e2ds_A.fits",
             "HARPS.2015-11-26T04_30_27.879_e2ds_A.fits"]

for test in list_test:
    print(re.sub(regex, subst, test))

Output :

HARPS.2010-10-19T02:24:55.819_e2ds_A.fits
HARPS.2016-01-20T00:38:12.300_e2ds_A.fits
HARPS.2015-11-26T04:30:27.879_e2ds_A.fits

Upvotes: 1

madmatrix
madmatrix

Reputation: 255

import re

inp = 'HARPS.2010-10-19T02_24_55.819_e2ds_A.fits'
m = re.search('(^.*T)(\d{2})_(\d{2})_(\d{2})(.*$)', inp)
if m:
    modified_val = ('%s%s:%s:%s%s' %
       (m.group(1), m.group(2), m.group(3), m.group(4), m.group(5)))

Upvotes: 0

Sushant
Sushant

Reputation: 3669

You could use python's replace function with count for number of replaces like -

str.replace("_", ":", 2) #where 2 is the number of instances of "_" 
# you want to replace in a string

Ex -

x = "HARPS.2010-10-19T02_24_55.819_e2ds_A.fits"
x = x.replace("_", ":", 2)
print(x) # prints HARPS.2010-10-19T02:24:55.819_e2ds_A.fits 

Upvotes: 1

BcK
BcK

Reputation: 2811

If your data is consistent,

import os

# iterate over your files
for fileName in os.listdir():
    newName = fileName[:-13].replace('_', ':') + fileName[-13:]
    os.rename(fileName, newName)

# 'HARPS.2010-10-19T02:24:55.819_e2ds_A.fits'
# 'HARPS.2016-01-20T00:38:12.300_e2ds_A.fits'
# 'HARPS.2015-11-26T04:30:27.879_e2ds_A.fits'

Upvotes: 2

Related Questions