Zac
Zac

Reputation: 323

CHange multiple file name python

I am having trouble with changing file name manually I have folder with lots of file with name like

202012_34324_3643.txt
202012_89543_0292.txt
202012_01920_1922.txt
202012_23442_0928.txt
202012_21346_0202.txt

what i want it to be renamed as below removing numbers before _ and after _ leaving number in between underscore.

34324.txt
89543.txt
01920.txt
23442.txt
21346.txt

i want a script that reads all files in the folder renames it like above mentioned. Thanks

Upvotes: 0

Views: 98

Answers (2)

nablag
nablag

Reputation: 176

You could try using the os library in python.

import os

# retrieve current files in the directory
fnames = os.listdir()
# split the string by '_' and access the middle index
new_names = [fnames.split('_')[1]+'.txt' for fname in fnames]

for oldname, newname in zip(fnames, new_names):
    os.rename(oldname, newname)

Upvotes: 3

simonarys
simonarys

Reputation: 55

This will do the work for the current directory.

import os

fnames = os.listdir()
for oldName in fnames:
    if oldName[-4:] == '.txt' and len(oldName) - len(oldName.replace("_","")) == 2:
        s = oldName.split('_')
        os.rename(oldName, s[1]+'_'+s[2]+'.txt')

Upvotes: 1

Related Questions