- 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
- 6 Best Ways to Get Filename Without Extension in Python
- How to get the filename?
- 1. Using splitext() to Get Filename Without Extension in Python
- The syntax of splitext() method is:
- The entire code is:
- 2. With the split() method to Get Filename Without Extension in Python
- 3. Using rfind() to Get Filename Without Extension in Python
- The syntax of the rfind() function is:
- 4. Using Basename() function to Get Filename Without Extension in Python
- The syntax of the function is:
- 5. Using pathlib.Path.stem() to Get Filename Without Extension in Python
- 6. By the rpartition() function to Get Filename Without Extension in Python
- The syntax of the rpartition() function is:
- How do I get the filename without the extension from a path in Python?
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.
📚 Discover Online Data Science Courses & Programs (Enroll for Free)
Introductory ⭐
Intermediate ⭐⭐⭐
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
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
Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.
6 Best Ways to Get Filename Without Extension in Python
Files are used for storing information with the ability to read and write on them. The operations which can be performed on files in python are – read, write, open, close, rename and delete. With the help of files, we can store information inside the computer’s storage. Each file has a pathname that tells about the location at which the file is stored. The pathname consists of information about the directory where the file is stored, the name of the file, and the extension with which the file is stored. In this article, we shall be looking at six different ways in python to get filename without extension.
How to get the filename?
As mentioned before, a pathname consists of three parts – the extension of the file, the filename, and the file’s location. First, we will have to separate the pathname and the extension. Then from the pathname, we shall separate the filename with the directory path. We shall be looking at 6 ways in python to get filename without extension.
1. Using splitext() to Get Filename Without Extension in Python
The splitext() method can be used to get filename in python without extension. The method is present in the os module of python. Using os.path module, we can use it to work with pathnames in python. With splitext(), we can split the entire pathname into two parts – the extension and the root.
The syntax of splitext() method is:
The function takes the pathname as an argument and returns a tuple containing the separated extension and root names.
Let us implement the function in python. First, we shall import the os module.
We have a variable named ‘directory’ which contains the complete path of out file.
directory = '/Users/Programs/Directory/program1.csv'
Now, we will call the splitext() method by os.path.splitext(). We shall pass the variable ‘directory’ inside the splitext() method. Since the method generates a tuple containing two parts, we shall save the extension into a variable named ‘extension’ and the rest of the path into a variable named ‘pathname’.
pathname, extension = os.path.splitext(directory)
If we try to print the output of os.path.splitext(), the tuple returned would be:
('/Users/Programs/Directory/program1', '.csv')
Now, we shall split the variable ‘path’ with the forward slash as the separator.
After that, we shall print the last item of the list ‘filename’, which will be the actual filename.
The output is:
The entire code is:
import os directory = '/Users/Programs/Directory/program1.csv' pathname, extension = os.path.splitext(directory) filename = pathname.split('/') print(filename[-1])
Here, if you want the complete pathname , you can simply skip splitting the variable ‘pathname’ and directly have it as the filename.
2. With the split() method to Get Filename Without Extension in Python
Similar to the splitext() method, we can also use the split() method to get filename without extension. For using the split() function, there is no need to import the os module. We will have to call the split() function twice.
First, we shall split the extension and the rest of the pathname. Then, we shall split the extension of the file. The separator for the first split() function will be the ‘.’ character and the separator for the second split() function will be the forward-slash ‘/’.
Here, after the first splitting, we will store the output into variable ‘name’. Then we shall split the first item of the list ‘name’ by using ‘name[0].split()’ with forward slash as the separator. Then we will print the last item of the list ‘filename’.
directory = '/Users/Programs/Directory/program1.csv' name = directory.split('.') filename = name[0].split('/') print(filename[-1])
The output is:
Here, if you want the complete pathname, we will simply print ‘name[0]’.
3. Using rfind() to Get Filename Without Extension in Python
We can also use the rfind() method to split the filename to separate the pathname and the extension. The function rfind() will find the last occurrence of the given value.
The syntax of the rfind() function is:
string.rfind(value, start, end)
We can all the rfind() method with a string. Here, a value is an item whose last occurrence has to be returned. The start and end represent the starting and ending positions while searching the string. By default, the start value is 0, and the end value is the length of the string.
Here, we will call the rfind() function using directory.rfind(). Inside the rfind() function, we shall pass the dot ‘.’ as the value. We shall save the index of the dot character into a variable named ‘index’. Then, we shall print the string ‘directory’ from the 0th character to the value of ‘index’.
directory = '/Users/Programs/Directory/program1.csv' index = directory.rfind(".") print(directory[:index])
The output is:
/Users/Programs/Directory/program1
If you only want the filename ‘program1’, then we can split() using the forward-slash character.
4. Using Basename() function to Get Filename Without Extension in Python
We can also use the basename() function from the os module to separate the filename. With the basename() function, we can get the base name of a file from the entire directory name.
The syntax of the function is:
We have to pass the entire pathname into the basename() function as an argument. First, we will import the os module.
The output of ‘os.path.basename(directory)’ will be ‘program1.csv’. So, we will call the split function and pass the dot character as the separator. That will return a list containing [ ‘program1’ , ‘csv’ ]. So we will print the first item of that list.
import os directory = '/Users/Programs/Directory/program1.csv' print(os.path.basename(directory).split('.')[0])
The output will be:
5. Using pathlib.Path.stem() to Get Filename Without Extension in Python
The pathlib module in python is used to deal with the file paths. When we don’t want to get the complete path, we can use pathlib.Path.stem(). Using the stem property, we will get the file name without its extension.
For that, first, we will have to import the pathlib module. Then we shall pass the ‘directory’ inside the pathlib.Path() function. Then, we shall use the stem property.
import pathlib directory = '/Users/Programs/Directory/program1.csv' filename = pathlib.Path(directory).stem print(filename)
The output filename is:
6. By the rpartition() function to Get Filename Without Extension in Python
The rpartition() function splits a given string into three parts. One part will be the separator and the other two parts will be the strings to the left and the right side of the separator.
The syntax of the rpartition() function is:
string.rpartition(separator)
directory = '/Users/Programs/Directory/program1.csv' print(directory.rpartition('.')[0])
/Users/Programs/Directory/program1
That is all for 6 ways in Python to Get Filename Without Extension. If you have any questions, let us know in the comments below.
Until next time, Keep Learning!
How do I get the filename without the extension from a path in Python?
To get the filename without the extension from a file path in Python, you can use the os.path.splitext() function. This function returns a tuple containing the file name and the file extension. You can then use string slicing to get just the file name.
import os file_path = '/path/to/file.txt' # Use os.path.splitext to split the file name and extension filename, file_ext = os.path.splitext(file_path) # Use slicing to get the file name without the extension filename_without_ext = filename[:-len(file_ext)] print(filename_without_ext) # Output: '/path/to/file'
Alternatively, you can use the os.path.basename() function to get the base name of the file, and then use string slicing to remove the extension. Here’s an example:
import os file_path = '/path/to/file.txt' # Get the base name of the file filename = os.path.basename(file_path) # Use slicing to remove the extension filename_without_ext = filename[:filename.rindex('.')] print(filename_without_ext) # Output: 'file'
Both of these methods assume that the file extension is separated from the rest of the file name by a period ( . ). If this is not the case, then you will need to use a different approach to split the file name and extension.