Python Get Filename From Path

In this Python tutorial, you will learn about Python to get a filename from a path.

While building the file management app in Python, at some point, I needed to implement the functionality of showing the file with their name. I used the Python ‘os’ module to get the file’s name to achieve that.

Additionally, I have shown different modules and methods for getting the filename from the path.

Python Get Filename From Path

There are four Python methods for getting the file name from the path: the ‘os’ module, the ‘pathlib’ module, split() and rsplit(), and regular expressions.

Let’s start.

Python File Name Using Os Module

The ‘os’ module in Python allows you to interact with operating systems. It has several functions that can be used to interact with operating system file systems.

The OS module contains a function called basename() in the submodule os.path. You must pass this function’s path to get the file name.

First, define the file’s path as shown in the code below.

file_path = "/home/user/documents/data.txt"

The file name is ‘data.txt’, so you can use the basename() function to extract this name from the path, as shown in the code below.

file_name = os.path.basename(file_path)

Now print the ‘file_name’ using the code below.

print(file_name)
Python File Name Using Os Module

Look at the output. The function basename() extracts the file name as ‘data.txt’ from the path “/home/user/documents/data.txt”.

Similarly, if you access a different file path, you can get the file name using the basename() function of the submodule os.path.

Python Path Get Filename Using Pathlib Module

The module ‘pathlib’ is a new module alternative to ‘os’, introduced in Python 3.4; it uses object-oriented concepts to file path systems.

READ:  Python Program to convert String to a List

To get the file name using the ‘pathlib’, you must use this module’s class ‘Path’. This class represents the file system path and provides different functions to operate on these paths, such as reading or writing content.

For example, first, you import the Path class, as shown in the code below.

from pathlib import Path

Then, define the file path as shown in the code below.

file_path = "/home/user/documents/editor.exe"

Then, pass the file_path to the Path() function, as shown in the code below.

path = Path(file_path)

After that, to get the file name, call the attribute ‘name’ on the ‘path’ as shown in the code below.

print(path.name)
Python Path Get Filename Using Pathlib Module

Look at the output: when the attribute ‘name’ is called on the ‘path’, it returns the file’s name from the path “/home/user/documents/editor.exe”.

This is how to use the file name using the pathlib module in Python.

Python Get Name of File Using the Regular Expression

A regular expression consists of a sequence of characters, which acts as a pattern to search for a string or subset of a string.

You can use a pattern to extract the file name from the path. The pattern is given below.

[\w]+?(?=\.)

Where,

  • [\w] : It matches the words within the set
  • +? : It match the string if it’s present only once before? keyword
  • (?=): It matches all characters without a newline and ensures to stop at.

For example, you have a path and pattern, which is defined below,

path = "/home/user/documents/data.zip"
pattern = '[\w-]+?(?=\.)'

To extract the file name, search the pattern in the specified path “/home/user/documents/data.zip”. As you can see, the path is the string value, so to search this pattern, you will need to use the search() function of the ‘re’ module in Python.

To use the search function, pass the pattern you want to search and the path (a string value), as shown in the code below.

import re
file_name = re.search(pattern, path)

To match the pattern to the string path, call the group() method on the ‘file_name’ as shown in the code below.

print(file_name.group())
Python Get Name of File Using the Regular Expression

Look at the output. The regular expression (pattern) returns the file name as ‘data’ without the extension.

READ:  How to count occurrences of a character in a Python list

Let’s understand the code part. This pattern, ‘ [w-] +? (? =.)’, represents the file name. Then, the search(pattern, path) method of the ‘re’ module is used to match this pattern with the file path, which is in string form.

This search() method takes two values: a pattern you want to search in the string, and the second is the string in which the pattern is searched, but here, the string value is the file’s path on your system.

Next, to match the pattern, the group() method is called on the object ‘file_name’, and this object is created using the search() method.

Thus, as a result, the file name as ‘data’ is returned without the file extension.

This is not the best method for extracting the file name from the path, but you can use it if you have no other choice.

This is how to get the name of the file using the regular expression.

Print File Name Python Using the Split() and Resplit() Method

The split() and rsplit() are two functions in Python that split the string into substrings based on the specified separator.

There is a subtle difference between split() and rsplit ().

  • split(separator, maxsplit): It splits the string into a list of substrings based on the specified separator; if the separator is not provided, it splits the string based on the whitespace by default.
  • rsplit (separator,maxsplit): The working of the rsplit() is the same as the rsplit(), but it splits the string from the right side of the string, or in simpler words, it starts the splitting of the string from the end.
READ:  Python Nested Dictionary to JSON

As you can see, both methods take the common argument maxsplit, which specifies the number of times you want to perform splitting . If you specify it as 1, it splits only once for a separator. If you do not provide this value, it will split by default for all the occurrences of the separator within the string.

Here, you need to apply the simple logic to extract the file name from the path; first, divide the path based on the separator ‘/’ using the split() method into a list of substrings.

Then, use the rsplit () to take the last substrings from the list and split that string based on the separator dot (.) into the list of substrings.

Then, take the first string from the list of substrings created by the rsplit(). This first substring represents the name of the file.

For example, define the file’s path as shown in the code below.

path = "/home/user/documents/sales.tar"

Then call the split() with separator as ‘\’ to divide the path into a list of substrings using the code below.

path_substring = path.split('/')
print(path_substring)

Then, take the last substring using the ‘path_substring[-1]’, then call the rsplit() with separator as dot (.) and perform splitting one time by specifying the maxsplit as 1 shown in the code below.

file_name = path_substring[-1].rsplit('.', 1)
print(file_name)

After executing the above code, the ‘file_name’ contains the file name and extension as a list of substrings. The file name is at the 0th index in the list, so to access it, use the code below.

print(file_name[0])
Print File Name Python Using the Split() and Resplit() Method

Look at the output. Using the split() and rsplit() together, the file name ‘sales’ is returned from the path.

This is how to print the file in Python using the split() and rsplit() functions together.

Conclusion

In this Python tutorial, you learned about Python to get a filename from a path using the four methods: the ‘os’ module, the ‘pathlib’ module, split() and rsplit (), and regular expressions.

You may like to read:

2 thoughts on “Python Get Filename From Path”

Comments are closed.