The Wayback Machine - https://web.archive.org/web/20250103080101/https://www.geeksforgeeks.org/python-program-to-get-the-file-name-from-the-file-path/
Open In App

Python Program to Get the File Name From the File Path

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

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 os
path = '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 os

file_path = 'C:/Users/test.txt'  # file path

# using basename function from os 
# module to print file name
file_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 os

file_path = 'C:/Users/test.txt'

file_name = os.path.basename(file_path)
file = os.path.splitext(file_name)

print(file)  # returns tuple of string

print(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. Although stem 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 Path

file_path = 'C:/Users/test.txt'

# stem attribute extracts the file
# name
print(Path(file_path).stem)

# name attribute returns full name
# of the file
print(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.

Example:

Python
import re

file_path = 'C:/Users/test.txt'
pattern = '[\w-]+?(?=\.)'

# searching the pattern
a = re.search(pattern, file_path)

# printing the match
print(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 usage
file_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



Next Article

Similar Reads

three90RightbarBannerImg