Python: Split File Path

Bruce Wen
1 min readJun 5, 2021

We often use file path in coding and we often need to split file path to get file name, file extension, parent folder as such. Here, this article will show how to do it.

Here is one example:

file_path = '/share/system/v2.0/src/main/java/Test.java'
split_parts = file_path.split('/')
file_name = split_parts[-1]
parent_folder_name = split_parts[-2]
file_extension = file_name.split('.')[-1]

Note: file_extension above will be only ‘java’, if you want ‘.java’, then, you need to add the dot.

file_extension = f".{file_name.split('.')[-1]}"

In the example, we used some methods of str and negative index of array.

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

In fact, if we just want to get the file extension, we can use another split method which split from right to left.

str.rsplit(sep=None, maxsplit=-1)
file_extension = file_path.rsplit('.', 1)[-1]

This will also returns java as value of file_extension . The 2nd argument of method rsplit tells how many split operation will be performed. In addition, rsplit method is to do the split operation from rightmost rather than leftmost which did by split method.

About negative index of array, -1 means the last index pointing to the last element in the array. If the array has 3 elements, then -3 means the first index number pointing to the first element in the array. That’s one special aspect in Python array.

Thanks for reading and happy programming!

--

--