Python Program to Get the File Name From the File Path - GeeksforGeeks (2024)

Last Updated : 21 Aug, 2024

Summarize

Comments

Improve

In this article, we will be looking at the program to get the file name from the given file path in the Python programming language. Sometimes during automation, we might need the file name extracted from the file path.

Better to have knowledge of:

  • Python OS-module
  • Python path module
  • Regular expressions
  • Built in rsplit()

Method 1: Python OS-module

Example1: Get the filename from the path without extension split()

Python’s split() function breaks the given text into a list of strings using the defined separator and returns a list of strings that have been divided by the provided separator.

Python
import ospath = 'D:\home\Riot Games\VALORANT\live\VALORANT.exe'print(os.path.basename(path).split('/')[-1])

Output:

VALORANT.exe

Example 2: Get the File Name From the File Path using os.path.basename

The base name in the given path can be obtained using the built-in Python function os.path.basename(). The function path.basename() accepts a path argument and returns the base name of the pathname path.

Python
import osfile_path = 'C:/Users/test.txt' # file path# using basename function from os # module to print file namefile_name = os.path.basename(file_path)print(file_name)

Output:

test.txt

Example 3: Get the File Name From the File Path using os.splitext

This method will end up with a file and it’s an extension but what if we need only the file name without an extension or only extensions. Here splitext function in the os module comes into the picture. This method will return a tuple of strings containing filename and text and we can access them with the help of indexing.

Example:

Python
import osfile_path = 'C:/Users/test.txt'file_name = os.path.basename(file_path)file = os.path.splitext(file_name)print(file) # returns tuple of stringprint(file[0] + file[1])

Output:

('test', '.txt')
test.txt

Method 2: Get the File Name From the File Path Using Pathlib

The Python Pathlib package offers a number of classes that describe file system paths with semantics suitable for many operating systems. The standard utility modules for Python include this module. Althoughstem is one of the utility attributes that enables extracts of the filename from the link without extension if we want an extension with the file we can use name attributes

Example:

Python
from pathlib import Pathfile_path = 'C:/Users/test.txt'# stem attribute extracts the file# nameprint(Path(file_path).stem)# name attribute returns full name# of the fileprint(Path(file_path).name)

Output:

test
test.txt

Method 3: Get the File Name From the File Path Using Regular expressions

We can use a regular expression to match the file name with the specific pattern.

Pattern - [\w]+?(?=\.)

This pattern is divided into 3 patterns

  • [\w] matches the words inside the set
  • +? matches the string if it’s present only once before ? keyword
  • (?=) matches all characters without newline and make sure to stop at.

Python Program to Get the File Name From the File Path - GeeksforGeeks (1)

Example:

Python
import refile_path = 'C:/Users/test.txt'pattern = '[\w-]+?(?=\.)'# searching the patterna = re.search(pattern, file_path)# printing the matchprint(a.group())

Output:

test

Method 4: Use the built-in Python function split() to split the file path into a list of individual components, and then use the rsplit() method:

you can use the built-in Python function split() to split the file path into a list of individual components, and then use the rsplit() method to split the last component (which should be the file name and extension) into a list containing the file name and extension. You can then use indexing to extract the file name from this list.

Here is an example of how this can be done:

Python
def get_file_name(file_path): file_path_components = file_path.split('/') file_name_and_extension = file_path_components[-1].rsplit('.', 1) return file_name_and_extension[0]# Example usagefile_path = 'C:/Users/test.txt'result = get_file_name(file_path)print(result) # Output: 'test'

Output: test

This approach first uses the split() function to split the file path into a list of individual components, separated by the ‘/’ character. The rsplit() method is then used to split the last component (which should be the file name and extension) into a list containing the file name and extension, using the ‘.’ character as the separator. The file name is then extracted from this list using indexing. This approach will work for any file path and extension, as long as the file path is in a format that can be parsed using the split() and rsplit() methods.

Python Program to Get the File Name From the File Path – FAQs

How to Get File Name from a Path in Python

To get the file name from a path in Python, you can use the os.path.basename() function from the os module. This function returns the base name (the last part of the path) which is the file name.

Example:

import os

path = '/path/to/your/file.txt'
file_name = os.path.basename(path)
print(file_name) # Output: file.txt

How to Get the Name of a Folder from a Directory Path in Python

To extract the folder name from a directory path, you can again use os.path.basename(). If the path ends with a trailing slash, you should first strip the slash to get the correct folder name.

Example:

import os

path = '/path/to/your/folder/'
# Remove trailing slash
if path.endswith('/'):
path = path[:-1]
folder_name = os.path.basename(path)
print(folder_name) # Output: folder

How to Get File Name from Path Without Extension in Python

To get the file name from a path without its extension, you can combine os.path.basename() with os.path.splitext() to strip the extension.

Example:

import os

path = '/path/to/your/file.txt'
base_name = os.path.basename(path)
file_name_without_extension, _ = os.path.splitext(base_name)
print(file_name_without_extension) # Output: file

How Do You Check If a File Name Is in a Directory in Python

To check if a specific file name is present in a directory, you can list all files in the directory using os.listdir() and then check if the file name is in that list.

Example:

import os

directory = '/path/to/your/directory'
file_to_check = 'file.txt'
files_in_directory = os.listdir(directory)
if file_to_check in files_in_directory:
print("File is in the directory")
else:
print("File is not in the directory")

How to Get Current Directory Name from Path in Python

If you need to get the name of the current directory from a path, you can use os.path.basename() in conjunction with os.getcwd() to obtain the current working directory and then extract the last part of it.

Example:

import os

current_directory_path = os.getcwd()
current_directory_name = os.path.basename(current_directory_path)
print(current_directory_name)

These methods provide robust solutions for handling file paths, directory names, and checking file presence within directories in Python, using built-in functions provided by the os module



shiv_ka_ansh

Python Program to Get the File Name From the File Path - GeeksforGeeks (3)

Improve

Previous Article

Rename a folder of images using Tkinter

Next Article

Finding the largest file in a directory using Python

Please Login to comment...

Python Program to Get the File Name From the File Path - GeeksforGeeks (2024)
Top Articles
Managing Sheet-Based Revisions with Ideate BIMLink
Special offer for Mint users - Quicken Simplifi | Quicken
Jack Doherty Lpsg
Netronline Taxes
Menards Thermal Fuse
Xre-02022
Paris 2024: Kellie Harrington has 'no more mountains' as double Olympic champion retires
Voorraad - Foodtrailers
Craigslist Free Stuff Appleton Wisconsin
Nesb Routing Number
Displays settings on Mac
Craigslist Labor Gigs Albuquerque
Top Hat Trailer Wiring Diagram
Shuiby aslam - ForeverMissed.com Online Memorials
Keniakoop
OpenXR support for IL-2 and DCS for Windows Mixed Reality VR headsets
Classroom 6x: A Game Changer In The Educational Landscape
Lima Funeral Home Bristol Ri Obituaries
Foodland Weekly Ad Waxahachie Tx
Pekin Soccer Tournament
1v1.LOL - Play Free Online | Spatial
Booknet.com Contract Marriage 2
Conan Exiles: Nahrung und Trinken finden und herstellen
Reborn Rich Kissasian
Purdue 247 Football
Play It Again Sports Norman Photos
Toothio Login
Obituaries Milwaukee Journal Sentinel
Wsbtv Fish And Game Report
Evil Dead Rise Showtimes Near Sierra Vista Cinemas 16
Tinyzonehd
Scott Surratt Salary
The Procurement Acronyms And Abbreviations That You Need To Know Short Forms Used In Procurement
Askhistorians Book List
How To Make Infinity On Calculator
Imperialism Flocabulary Quiz Answers
Are you ready for some football? Zag Alum Justin Lange Forges Career in NFL
Restored Republic December 9 2022
Bismarck Mandan Mugshots
Mvnt Merchant Services
Ashoke K Maitra. Adviser to CMD's. Received Lifetime Achievement Award in HRD on LinkedIn: #hr #hrd #coaching #mentoring #career #jobs #mba #mbafreshers #sales…
Postgraduate | Student Recruitment
Todd Gutner Salary
Natasha Tosini Bikini
Pgecom
Theater X Orange Heights Florida
Vci Classified Paducah
Hdmovie2 Sbs
Shannon Sharpe Pointing Gif
Ark Silica Pearls Gfi
BYU Football: Instant Observations From Blowout Win At Wyoming
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated:

Views: 5480

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.