-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?

8
  • 2
    How have you tried to do it, and what is the problem with your current implementation? Commented Dec 27, 2018 at 17:55
  • 1
    Just to clarify, you want to end up with _file.extension ? Commented Dec 27, 2018 at 17:59
  • 1
    extracting-extension-from-filename-in-python && general string splitting && 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 Commented Dec 27, 2018 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. Commented Dec 27, 2018 at 18:00
  • 1
    Separate off the extension. Split the string on the underscore character. Then put everything back together ignoring the last item from the split. Commented Dec 27, 2018 at 18:04

1 Answer 1

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

Comments

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.