-2

I have a list of file like the following

'TRIAL_20134_75690_TOTAL_2018-08-12-17-18.csv'

I want to rename them the parte after the last underscore, such as the file will be renamed like:

'TRIAL_20134_75690_TOTAL.csv'
emax
  • 6,965
  • 19
  • 74
  • 141
  • Check this out: https://stackoverflow.com/questions/225735/batch-renaming-of-files-in-a-directory – Clujio Aug 30 '18 at 11:55
  • The [os](https://docs.python.org/3/library/os.html) and [shutil](https://docs.python.org/3/library/shutil.html) modules in the standard library have functions that do this sort of thing. It's worth checking out if there's something helpful [in the standard library](https://docs.python.org/3/library/index.html) _before_ asking SO. – David Maze Aug 30 '18 at 12:00
  • @DavidMaze I not everyone has the same philosophy as me, but in the time it took you to write the comment, I just got the guy on his way. :p – Joe Iddon Aug 30 '18 at 12:03

1 Answers1

0

Use os.rename from the os library to do the renaming.

To get the sting up to the last index of an underscore (_), use the rindex method of string.

You also need to concatenate the extension back on.

I.e.

import os
f = 'TRIAL_20134_75690_TOTAL_2018-08-12-17-18.csv'
os.rename(f, f[:f.rindex('_'] + '.csv')
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54