0

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

2 Answers 2

3

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

Comments

1

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

1 Comment

i found that some file has same name in middle how can i just remove first words before _. example: 2344_4234_4324.txt => 4234_4324.txt

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.