- How to get file name from a path in Python?
- How to get the file name from Path in Python
- Method 1: Using os.path.basename()
- Method 2: Using pathlib.Path()
- Method 3: Using string splitting
- Handling Edge Cases
- 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
- Извлечь имя файла из пути для любого формата ОС/пути
- Извлечение имени файла из путей к файлам для платформо-независимых решений
- Способ 1: Использование метода rsplit()
- Способ 2: Использование функции basename() из модуля ОС
- Способ 3: использование модуля пути в 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:
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:
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.
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.
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.
Извлечь имя файла из пути для любого формата ОС/пути
В Python мы можем легко извлечь имя файла из всего пути к файлу, используя встроенные функции и библиотеки. Вам может быть интересно, почему вам нужно извлекать имена файлов из абсолютного пути к файлу в Python. Ответ заключается в том, что разные компьютерные системы используют разные разделители для разных файловых систем. Во время автоматизации, которая распространена в настоящее время, очень важно без проблем разделять имена файлов.
Извлечение имени файла из путей к файлам для платформо-независимых решений
Нам необходимо извлечь имена из путей к файлам, чтобы получить независимые от платформы решения вышеуказанной проблемы. Есть много способов сделать это, например:
Давайте посмотрим, как мы можем реализовать все вышеперечисленные методы один за другим.
В Python вы можете извлечь имя файла из пути к файлу, используя различные методы, такие как метод rsplit(), функцию basename() из модуля ОС и модуль Path. Эти методы не зависят от платформы и могут использоваться для обработки различных файловых систем и разделителей в различных компьютерных системах во время автоматизации. Каждый метод имеет свой синтаксис, и вы можете выбрать тот, который соответствует вашим требованиям.
Способ 1: Использование метода rsplit()
Метод rsplit() похож на метод split(), но он разделяет слова или символы, начиная справа, а не слева. Он возвращает список слов или символов в строке, разделенных разделителем. Синтаксис функции:
our_string.rsplit(separator,maxsplit)
Разделитель — это разделитель, который может быть любым символом, если он указан. Значение по умолчанию для этого параметра — пробел.
Параметр maxsplit определяет количество сплитов, которые необходимо выполнить. Это необязательный аргумент. Его значение по умолчанию равно -1, что разделяет все отдельные элементы. Давайте посмотрим на код того же самого. Вам не нужно устанавливать ничего дополнительно, чтобы использовать эту функцию.
#code for extracting file name #taking input for file path file_name=input("Enter the absolute path of your file=") #spliting the entire file path filename_compo=file_name.split('/') #using rsplit() to separate file name file_name_extracted = filename_compo[-1].rsplit('.', 1) #displaying only the file name print("The file name is wp-block-syntaxhighlighter-code ">Enter the absolute path of your file=C:/Downloads/askpython_files.txt The file name is= askpython_files
Предложено: что такое переменная __file__ в Python?
Способ 2: Использование функции basename() из модуля ОС
Модуль операционной системы (ОС) в Python содержит различные функции, которые могут устанавливать соединения между операционной системой и пользователем. Мы будем использовать функцию basename() из этого модуля, которая может извлечь базовое имя файла. Нет необходимости устанавливать или загружать какие-либо дополнительные библиотеки, чтобы использовать эту функцию, поскольку она входит в стандартные служебные модули Python. Его синтаксис:
os.path.basename(path_of_the_file)Код, используемый для извлечения имени файла:
#code for extracting file name #importing required modules import os #taking input for file path file_abpath=input("Enter the absolute path of your file=") #using the basename function from the os module file_nameextracted = os.path.basename(file_abpath) #returns the tuple containing the file file_final = os.path.splitext(file_nameextracted) #only the first index print("The filename is wp-block-syntaxhighlighter-code ">Enter the absolute path of your file=C:/users/shreya/downloads/myfolder.txt The filename is= myfolderСпособ 3: использование модуля пути в Python
Это еще один метод, который можно использовать для получения имени файла из абсолютного пути к файлу на компьютере. Модуль Path в Python позволяет нам представлять экземпляры классов с семантикой, подходящей для разных операционных систем, что делает его универсальным решением для работы с путями к файлам.
Следующим образом мы можем использовать модуль пути для извлечения имени файла из пути в python.
#code for extracting file name #importing required modules from pathlib import Path file_path = input("enter absolute file path=") # the name attribute returns full name of the file print("The name of the file is wp-block-syntaxhighlighter-code ">enter absolute file path=C:/downloads/myfolder/firstprogram.py The name of the file is= firstprogram.pyПроверьте: конвертируйте PDF в файл TXT с помощью Python.
Заключение:
В этом руководстве мы рассмотрели различные методы извлечения имен файлов из абсолютных путей к файлам в Python. Имея несколько доступных библиотек, вы можете выбрать метод, который лучше всего соответствует вашим потребностям. Поскольку вы продолжаете работать с файлами, как вы можете интегрировать эти методы в свои проекты для удобной обработки файлов и автоматизации?