How about using the proper path handling methods from os.path?

>>> f = 'C:\\X\\Data\\foo.txt'
>>> import os
>>> os.path.basename(f)
'foo.txt'
>>> os.path.dirname(f)
'C:\\X\\Data'
>>> os.path.splitext(f)
('C:\\X\\Data\\foo', '.txt')
>>> os.path.splitext(os.path.basename(f))
('foo', '.txt')
Answer from Martlark on Stack Overflow
Top answer
1 of 5
13

The following should work for you

s="Planning_Group_20180108.ind"
'_'.join(s.split('_')[:-1])

This way you create a list which is the string split at the _. With the [:-1] you remove the last part. '_'.join() combines your list elements in the resulting list.

2 of 5
4

First I would extract filename itself. I'd split it from the extension. You can go easy way by doing:

path = "Planning_Group_20180108.ind"
filename, ext = path.split(".")

It is assuming that path is actually only a filename and extension. If I'd want to stay safe and platform independent, I'd use os module for that:

fullpath = "this/could/be/a/full/path/Planning_Group_20180108.ind"
path, filename = os.path.split(fullpath)

And then extract "root" and extension:

root, ext = os.path.splitext(filename)

That should leave me with Planning_Group_20180108 as root. To discard "_20180108" we need to split string by "_" delimiter, going from the right end, and do it only once. I would use .rsplit() method of string, which lets me specify delimiter, and number of times I want to make splits.

what_i_want, the_rest = root.rsplit("_", 1)

what_i_want should contain left side of Planning_Group_20180108 cut in place of first "_" counting from right side, so it should be Planning_Group

The more compact way of writing the same, but not that easy to read, would be:

what_i_want = os.path.splitext(os.path.split("/my/path/to/Planning_Group_20180108.ind")[1])[0].rsplit("_", 1)

PS. You may skip the part with extracting root and extension if you're sure, that extension will not contain underscore. If you're unsure of that, this step will be necessary. Also you need to think of case with multiple extensions, like /path/to/file/which_has_a.lot.of.periods.and_extentions. In that case would you like to get which_has_a.lot.of.periods.and, or which_has? Think of it while planning your app. If you need latter, you may want to extract root by doing filename.split(".", 1) instead of using os.path.splitext()

reference:

os.path.split(path),

os.path.splitext(path)

str.rsplit(sep=None, maxsplit=-1)

Discussions

splitting filenames names on underscore
You can use either os.path.basename or pathlib.Path.name: path = os.path.basename(line) path.split(sep, 1)[0] # Or path = Path(line).name path.split(sep, 1)[0] More on reddit.com
🌐 r/learnpython
7
1
October 29, 2019
Split a string by a delimiter in Python - Stack Overflow
Use with AICopyW, X, Y, Z = filename.split('_') W = 'file' X = 'foo' Y = 'bar' Z = 'fox' ... Save this answer. ... Show activity on this post. When you want to split a string by a specific delimiter like: __ or | or , etc. it's much easier and faster to split using .split() method as in the top answer because Python ... More on stackoverflow.com
🌐 stackoverflow.com
Splitting filenames for their first word in Python - Geographic Information Systems Stack Exchange
I have 2 shapefiles, each one placed in a different folder: "C:\...\Folder O\Germany (O).shp" "C:\...\Folder P\Germany Berlin (P).shp" The following script finds the shapefile... More on gis.stackexchange.com
🌐 gis.stackexchange.com
April 21, 2015
python - split a file name - Stack Overflow
How do i write a python script to split a file name eg LN0001_07272010_3.dat and to rename the file to LN0001_JY_07272010? also how do i place a '|' and the end of each line in this file(contents) More on stackoverflow.com
🌐 stackoverflow.com
🌐
Not Defined Tech
notdefined.tech › blog › splitting-extension-from-filenames-in-python
The Best Ways to Separate Filename and Extension in Python
March 26, 2025 - Here's where we start running into complexity by treating the filename as a string and simply cutting up the parts: >>> filename = "this.something.png" >>> name_fragments = filename.split('.') >>> name_fragments ['this', 'something', 'png'] >>> ".".join(name_fragments[:-1]) 'this.something'
🌐
Note.nkmk.me
note.nkmk.me › home › python
Get the Filename, Directory, Extension from a Path String in Python | note.nkmk.me
May 8, 2023 - If you want to split by the first (left) dot ., use split(). Split a string in Python (delimiter, line break, regex, and more) filepath_tar_gz = './dir/subdir/filename.tar.gz' print(os.path.splitext(os.path.basename(filepath_tar_gz))[0]) # ...
🌐
Reddit
reddit.com › r/learnpython › splitting filenames names on underscore
r/learnpython on Reddit: splitting filenames names on underscore
October 29, 2019 -

I have a bunch of files in a zip file with the following format a_b_c.ext what i want is for the code to do two things. First is to check for a certain type of extension. Second is to split the file names at the first '_' and only keep the string before the first underscore. I know how to do the former but not the latter. So far I have something like this

import os

from zipfile import ZipFile

with ZipFile('foo.zip', 'r') as f:

    filenames = f.namelist()

    for line in filenames:

        if line.endswith('.foo') or line.endswith('.foo2'):

            sep = '_'

            rest_of_string = line.split(sep,1)[0]

            print(rest_of_string)

This gives me foldername/part of file name I want. How do I get it to return just part of file name I want?

🌐
Homedutech
homedutech.com › faq › python › split-filenames-with-python.html
Split filenames with python
You can use the str.split() method to split a filename by a delimiter, such as a dot, to separate the root and extension.
🌐
Real Python
realpython.com › python-split-string
How to Split a String in Python – Real Python
February 5, 2025 - The .split() method in Python is a versatile tool that allows you to divide a string into a list of substrings based on a specified delimiter. By default, .split() separates a string at each occurrence of whitespace, which includes spaces, tabs, ...
Find elsewhere
🌐
Python
docs.python.org › 3 › library › os.path.html
os.path — Common pathname manipulations — Python 3.15.2 documentation
Split the pathname path into a 3-item tuple (drive, root, tail) where drive is a device name or mount point, root is a string of separators after the drive, and tail is everything after the root. Any of these items may be the empty string.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-os-path-splitext-method
Python os.path.splitext() method - GeeksforGeeks
July 11, 2025 - import os # path path = '/home/User/Desktop/file.txt' # Split the path in # root and ext pair root_ext = os.path.splitext(path) # print root and ext # of the specified path print("root part of '% s':" % path, root_ext[0]) print("ext part of '% s':" % path, root_ext[1], "\n") # path path = '/home/User/Desktop/' # Split the path in # root and ext pair root_ext = os.path.splitext(path) # print root and ext # of the specified path print("root part of '% s':" % path, root_ext[0]) print("ext part of '% s':" % path, root_ext[1])
🌐
Real Python
realpython.com › lessons › splitting-with-delimiter
Splitting With a Delimiter (Video) – Real Python
02:25 Handling file paths is another great example as file paths use forward slashes on Mac or Linux and backslashes on Windows. Just make sure you use the correct slash as the delimiter when splitting file paths.
Published: September 9, 2025
🌐
YouTube
youtube.com › watch
How to split filename and extension in Python - YouTube
How to split filename and extension in Python
Published: January 10, 2022
🌐
Thinkbox Software
docs.thinkboxsoftware.com › products › draft › 1.6 › Documentation › Cookbook › DeadlineIntegration › ParsingFileNamesToExtrachShotInformation.html
Parsing File Names to Extract Shot Information — Draft 1.6.8 documentation
This is obviously extendable to any number of splits (splitResult will have one element for each split it makes), and different separators (simply change the split argument to be your delimiter).
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-os-path-split-method
os.path.split() method - Python - GeeksforGeeks
July 11, 2025 - Return Type: This method returns a tuple that represents head and tail of the specified path name. In this example, the code demonstrates the use of os.path.split() method to split a given file path into its directory (head) and file/directory ...
🌐
Quora
quora.com › What-does-this-line-of-code-do-in-Python-filename-filename-split-0
What does this line of code do in Python, filename = filename.split(.) [0]? - Quora
Answer (1 of 2): this works in windows but will not work in Linux. As in Linux, a filename can be without an “extension name” Now you can guess a little bit… It’s about getting the first part of a filename after separating the filename by a period (.). But for the above-mentioned reason, ...