-3

I have a great number of files whose names are structured as follows:

this_is_a_file.extension

I got to strip them of what begins with the last underscore (included), preserving the extension, and save the file with the new name into another directory.

Note that these names have variable length, so I cannot leverage single characters' position.

Also, they have a different number of underscores, otherwise I'd have applied something similar: split a file name

How can I do it?

MadHatter
  • 638
  • 9
  • 23
  • 2
    How have you tried to do it, and what is the problem with your current implementation? – jonrsharpe Dec 27 '18 at 17:55
  • 1
    Just to clarify, you want to end up with `_file.extension` ? – Emilio Garcia Dec 27 '18 at 17:59
  • 1
    [extracting-extension-from-filename-in-python](https://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python) && general string splitting && [how-can-i-extract-the-folder-path-from-file-path-in-python](https://stackoverflow.com/questions/17057544/how-can-i-extract-the-folder-path-from-file-path-in-python) && `os.walk` && `import os` + it's methods && [rename-and-move-file-with-python](https://stackoverflow.com/questions/42541748/rename-and-move-file-with-python) – Patrick Artner Dec 27 '18 at 18:00
  • @jonrsharpe: edited my question. The different number of underscores is the major hindrance: I'm having troubles in figuring out how to handle it. – MadHatter Dec 27 '18 at 18:00
  • @emilio: No, the final result should be: `this_is_a.extension`. Thanks. – MadHatter Dec 27 '18 at 18:01
  • @patrick: thanks, reading right now. If they answer my question I'll close it. – MadHatter Dec 27 '18 at 18:02
  • 1
    Separate off the extension. Split the string on the underscore character. Then put everything back together ignoring the last item from the split. – hostingutilities.com Dec 27 '18 at 18:04
  • @MadHatter that doesn't really answer my question. Give a [mcve] showing how you've adapted the many existing examples. – jonrsharpe Dec 27 '18 at 18:04

1 Answers1

1

You could create a function that splits the original filename along underscores, and splits the last segment along periods. Then you can join it all back together again like so:

def myJoin(filename):
    splitFilename=filename.split('_')
    extension=splitFilename[-1].split('.')
    splitFilename.pop(-1)
    return('_'.join(splitFilename)+'.'+extension[-1])

Some examples to show it working:

>>> p="this_is_a_file.extension"
>>> myJoin(p)
'this_is_a.extension'
>>> q="this_is_a_file_with_more_segments.extension"
>>> myJoin(q)
'this_is_a_file_with_more.extension'
Emilio Garcia
  • 554
  • 1
  • 5
  • 20