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

Zac
  • 323
  • 7
  • 14

2 Answers2

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)
simonarys
  • 55
  • 1
  • 6
nablag
  • 176
  • 1
  • 7
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')
simonarys
  • 55
  • 1
  • 6
  • 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 – Zac Dec 12 '20 at 19:17