Python parse file path

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.

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.

Читайте также:  Can you create games with java

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.

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!

Источник

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.

Источник

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