Getting file name python

How to get file name from a path in Python?

In this Python tutorial, we will discuss, different ways to get file name from a path in Python. Not only this, I will also show you how to get the file extension from the file name in Python. Finally, we will discuss, how to get the file name without extension in Python.

How to get the file name from Path in Python

Here we will see at least 3 different ways to get the file name from path in Python.

Let’s consider an example file path: /home/user/documents/sample.txt . Here, sample.txt is the file name that we are interested in extracting. Below, we will explore different methods to achieve this.

Method 1: Using os.path.basename()

The os module in Python provides a plethora of functions to interact with the operating system. The os.path.basename() function can be used to extract the filename from a path.

import os file_path = "/home/user/documents/sample.txt" file_name = os.path.basename(file_path) print(file_name) # Output: sample.txt 

Here, the os.path.basename() function takes the file path as an argument and returns the base name, i.e., the file name. Check the screenshot below for the output:

python file name

Method 2: Using pathlib.Path()

pathlib is a module in Python 3, which is object-oriented and a more modern approach to handling filesystem paths. It’s recommended to use pathlib over os.path for improved readability and simplicity.

from pathlib import Path file_path = Path("/home/user/documents/sample.txt") file_name = file_path.name print(file_name) # Output: sample.txt

In this example, we create a Path object with the file path as an argument and then use the name attribute to obtain the file name.

Check the screenshot below for the output:

get filename python

Method 3: Using string splitting

This method is less reliable and not recommended for use in production code, but for the sake of completeness, we can also split the string to extract the filename.

file_path = "/home/user/documents/sample.txt" file_name = file_path.split('/')[-1] print(file_name) # Output: sample.txt 

Here, we split the file path string by the delimiter / and select the last element in the resulting list. This method is not recommended because it relies on a fixed delimiter and can cause issues with different operating systems.

Читайте также:  Html and css fonts

Handling Edge Cases

The methods above work well for standard file paths, but what if the file path ends with a directory separator ( / or \ depending on the OS)? In such cases, the first two methods are robust enough to handle them, but the string splitting method will fail.

Let’s demonstrate this with an example:

import os from pathlib import Path file_path = "/home/user/documents/directory/" # Using os.path.basename() file_name_os = os.path.basename(file_path.rstrip(os.path.sep)) print(file_name_os) # Output: directory # Using pathlib.Path() file_path_obj = Path(file_path) file_name_pathlib = file_path_obj.name if file_path_obj.is_dir() else file_path_obj.parent.name print(file_name_pathlib) # Output: directory 

The os.path.basename() method can handle this by stripping the directory separator at the end before processing. For pathlib , we check if the path is a directory; if so, we extract the name, otherwise, we use the parent directory’s name.

You may like the following Python tutorials:

In this Python tutorial, we discuss how to get the file name from the path in Python.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

03 Methods to Get Filename from Path in Python (with code)

03 Methods to Get Filename from Path in Python (with code)

There are many occasions where during coding you will have to deal with files. In many competitive coding scenarios too, you will come across input files that will be provided to you for testing. Handling files in any programming language is an essential skill that must be learned by every coder.

The first step in file handling is being able to parse the filename from the user. When a file is supposed to be read in a program, how do we access it? So, we will find out here How do I get the filename from the path in Python? We listed both ways for with and without extension.

What are Filename and Path?

Filename and path are two terminologies that are associated with file handling. As the name suggests, the filename refers to the name of the actual file whereas the path refers to the exact location of a file.

Читайте также:  Разметка таблицы html документа

The contents of a file can only be accessed by its name. But the OS or the operating software we use does not store the file name as a single entity.

For example, if we want to go to our university, then our university is the filename, and the set of directions required to reach it is the path. Let us take the same example we took above to understand this concept:

Here what do you think is the filename? The file name in this example is file1.txt. An easy way to find out the file name is to look for the part that has an extension. An extension is nothing but a combination of a few letters after a file name.

In this example, file1.txt is the file name because it has a file extension .txt. Different files have different extensions based on the type of files they are. A text file would be .txt, a PowerPoint presentation would be .ppt, a word document would be .docx, and so on.

Therefore by finding the extension we can find the file name. But what about the remaining part? The remaining part after we remove the file path gives the location of the file within the system of the user.

In this example, it tells us that the file1.txt file is stored inside the Documents folder, which is stored inside the User1 folder, which itself is stored inside the Users folder which is lastly stored on the C drive of the computer. The entire name, the remaining part, and the file name together are called the Path.

But how do I read a filename from the path in Python?

03 Methods to get filename from path in Python

There are three methods that we can use to get the filename from a given path in python. Some of these methods use built-in functions, others use a module. A module is a collection of predefined functions that we can directly include in our code.

01) Split function in python

Any path that is passed to the interpreter will be a string value. A string value in python is nothing but a combination of characters. When a path is passed as an input, it will look like C:\Users\User1\Documents\file1.txt

Now we can use the built-in split function in python to split the path name. We will split the path name at every \. Once we do that, we will have a tuple that contains all the words between the slashes. Then we print the last element of the tuple and we get the filename with the extension.

Читайте также:  Using python script blender

We can further split the last element at the dot (.) to get just the filename and not the extension. The code implementation for this method to extract the filename from the path is shown below:

file_path = "C:/Users/User1/Documents/file1.txt" file_name = file_path.split("/")[-1] print(file_name)

02) OS module in python

As the name suggests, the OS module in python provides special functions and methods for operating system functionality like filename extraction. We can use the os.path.basename function to get the filename from the path given by the user.

Further, we can use the os.path.splitext function to get the filename without the extension. The code implementation using the os module is given below:

import os file_path = "C:/Users/User1/Documents/file1.txt" full_name = os.path.basename(file_path) file_name = os.path.splitext(full_name) print(full_name) print(file_name[0])

03) Using the Pathlib module in python

Besides the OS library, python also provides a library that is dedicated to handling different types of paths provided by different operating systems. Inside the pathlib library, we can use the Path function to get the filename from a given path.

The Path function has two attributes: stem and name. The stem attribute gives the filename without the extension and the name attribute gives the complete filename along with the extension. The code implementation using the path function is shown below:

from pathlib import Path file_path = "C:/Users/User1/Documents/file1.txt" full_name = Path(file_path).name file_name = Path(file_path).stem print(full_name) print(file_name)

Takeaways

Filename and path are important to be able to read and parse input from a file. Without the filename, it is impossible to read the contents or perform operations on the file. We learned 03 methods to get the filename from the path in python. We also provided the source code to do it yourself. Try it now!

Источник

Оцените статью