- Python: Get Filename From Path (Windows, Mac & Linux)
- How Are Paths Different in Windows and Mac/Linux?
- Use the os splittext Method in Python to Get the Filename from a Path
- Get the Filename from a Path without the Extension
- Use Python split to Get the Filename from a Path
- Use Python Pathlib to Get the Filename from a Path
- Conclusion
- Python – Get Filename from Path with Examples
- How to get the filename from a path in Python?
- 1. Using os module
- Filename from os.path.basename()
- Filename from os.path.split()
- 2. Using pathlib module
- Author
Python: Get Filename From Path (Windows, Mac & Linux)
In this tutorial, you’ll learn how to use Python to get a filename from a path for a given file. You’ll learn how to do this using Windows, Mac, and Linux. Paths consist of three main parts: the directory, the filename, and the extension. The directory tells us where the file is, the filename tells us what the file is called, and the extension is the file type. Knowing how to get a filename can be an important skill when you’re trying to process different files.
You’ll learn how to get the filename form a Python path using the os library, the string .split() method, and the popular pathlib library.
The Quick Answer: Use os splittext() or pathlib
How Are Paths Different in Windows and Mac/Linux?
Paths in Windows are different than they are in Mac and Linux operating systems. A key difference is the path separator the operating systems use. A path separator separates the directories from one another and allows us to identify the path of a file.
A Windows based operating system uses the backslash \ to separate paths. Meanwhile, Linux and Mac operating systems use the slash / to separate paths.
The problem with this is that the backslash is actually the escape character. Because of this, it can be helpful when working with paths, such as with string methods, to turn the string that contains our path into a raw string. This can be done by prepending the letter r to the front of a string.
Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.
Use the os splittext Method in Python to Get the Filename from a Path
The built-in os library comes with a helpful module, the pathname module, that allows us to work with system paths. The pathname module comes with a helpful function, the basename() function. This returns the base name of the file, meaning that it also returns the extension of the file.
Let’s take a look at what this looks like:
# Get filename from path using os import os path = "/Users/datagy/Desktop/SomeImportantFile.py" filename = os.path.basename(path) print(filename) # Returns: SomeImportantFile.py
We can see here that the script has returned the filename as well as the extension of the file.
Get the Filename from a Path without the Extension
If we wanted to remove the extension, we could write the following:
# Get filename from path using os import os path = "/Users/datagy/Desktop/SomeImportantFile.py" filename_with_extension = os.path.basename(path) filename = filename_with_extension.split('.', 1)[0] print(filename) # Returns: SomeImportantFile
This works because when we split the text and grab the first item, we only include the filename, rather than the extension as well. We pass in the second argument into the .split() function as the maxsplit= argument to tell Python how often to split the text.
In the next section, you’ll learn how to use the string .split() method to get the filename from a path in Python.
Want to learn how to get a file’s extension in Python? This tutorial will teach you how to use the os and pathlib libraries to do just that!
Use Python split to Get the Filename from a Path
We can get a filename from a path using only string methods, in particular the str.split() method. This method will vary a bit depending on the operating system you use.
In the example below, we’ll work with a Mac path and get the filename:
# Get filename from path using string methods path = "/Users/datagy/Desktop/SomeImportantFile.py" filename = path.split('/')[-1] print(filename) # Returns: SomeImportantFile.py
This returns the filename with the extension. If we wanted to return only the filename without the extension, we can simply split the filename again, this time using the . character.
Let’s take a look at what this would look like:
# Get filename from path using string methods path = "/Users/datagy/Desktop/SomeImportantFile.py" filename_with_extension = path.split('/')[-1] filename = filename_with_extension.split('.')[0] print(filename) # Returns: SomeImportantFile
In the next section, you’ll learn how to use the object-oriented pathlib library to get the filename form a Python path.
Need to automate renaming files? Check out this in-depth guide on using pathlib to rename files. More of a visual learner, the entire tutorial is also available as a video in the post!
Use Python Pathlib to Get the Filename from a Path
The pathlib library uses a bit of a different approach to handling paths than the other methods we’ve covered so far. In fact, it uses an object-oriented approach to handle file paths. This is great, as it means that once we generate a path object, we can easily access different attributes about it.
One of these attributes is the .stem attribute, that provides the filename of a provided path object.
Let’s take a look at how we can accomplish this in Python:
# Get filename from path using pathlib import pathlib path = "/Users/datagy/Desktop/SomeImportantFile.py" path_object = pathlib.Path(path) filename = path_object.stem print(filename) # Returns: SomeImportantFile
This approach is a bit different and for users not familiar with object-oriented design, it may seem a bit strange. But it is a very easy and intuitive approach, once you get the hang of it.
Conclusion
In this post, you learned how to use Python to get the filename from a path, in Windows, Mac, and Linux. You learned how to use the helpful os library to accomplish this, as well as some trickier string methods. You also learned how to use the more modern, object-oriented pathlib library to get the filename from a path.
To learn more about the pathlib library, check out the official documentation here.
Python – Get Filename from Path with Examples
In this tutorial, we will look at how to get the filename from a path using Python.
How to get the filename from a path in Python?
There are a number of ways to get the filename from its path in python. You can use the os module’s os.path.basename() function or os.path.split() function. You can also use the pathlib module to get the file name.
Let look at the above-mentioned methods with the help of examples. We will be trying to get the filename of a locally saved CSV file in python.
1. Using os module
The os module comes with a number of useful functions for interacting with the file system. You can use the following functions from the os to get the filename.
Filename from os.path.basename()
The os.path.basename() function gives the base filename from the passed path. For example, let’s use it to get the file name of a CSV file stored locally.
import os # the absoulte path of the file file_path = r"C:\Users\piyush\Documents\Projects\movie_reviews_data\IMDB Dataset 5k.csv" # get the filename print(os.path.basename(file_path))
You can see that we get the filename along with its extension as a string. To get the filename without its extension you can simply split the text on “.” and take the first part.
# filename without extension print(os.path.basename(file_path).split(".")[0])
You might also be interested in knowing how to Get File size using Python
Filename from os.path.split()
You can also use the os.path.split() function to get the filename. It is used to split the pathname into two parts – head and tail, where the tail is the last pathname component and the head is everything leading up to that. For example, for the path a/b/c.txt , the tail would be c.txt and the head would be a/b
Let’s now use it to find the filename of the CSV file from its path.
# the absoulte path of the file file_path = r"C:\Users\piyush\Documents\Projects\movie_reviews_data\IMDB Dataset 5k.csv" # split the file path head, tail = os.path.split(file_path) # get the filename print(tail)
You can see that the tail gives us the filename. Let’s now go ahead and see what do we have in the head part.
# show the path head print(head)
C:\Users\piyush\Documents\Projects\movie_reviews_data
The head contains the part of the file path leading up to the filename. Note that the os.path.split() function determines the head and tail based on the occurrence of the last directory separator \ or / depending on the OS. For example, if the path ends in a separator it will give an empty string as the tail.
For more on the os.path.split() function, refer to its documentation.
2. Using pathlib module
For python versions 3.4 and above, you can also use the pathlib module to interact with the file system in python. Among other things, you can use it to get the filename from a path. For example, let’s get the filename of the same CSV file used above.
from pathlib import Path # the absoulte path of the file file_path = r"C:\Users\piyush\Documents\Projects\movie_reviews_data\IMDB Dataset 5k.csv" # get the filename print(Path(file_path).name)
You can see that we get the correct filename using the name attribute of Path .
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel.
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts