Algorithm


  1. Input: Take the file path as input from the user or as an argument to a function.

  2. Identify Separator: Determine the file path separator based on the operating system (\ for Windows and / for Unix-like systems).

  3. Split Path: Use the split method to split the file path into a list of directories and the file name. The last element of this list will be the file name.

  4. Retrieve File Name: Extract the last element from the list obtained in step 3 to get the file name.

  5. Output: Display or return the file name obtained.

 

Code Examples

#1 Code Example- Using os module

Code - Python Programming

import os

# file name with extension
file_name = os.path.basename('/root/file.ext')

# file name without extension
print(os.path.splitext(file_name)[0])
Copy The Code & Try With Live Editor

Output

x
+
cmd
file

#2 Code Example with Python Programming

Code - Python Programming

import os

print(os.path.splitext(file_name))
Copy The Code & Try With Live Editor

Output

x
+
cmd
('file', '.ext')

#3 Code Example- Using Path module

Code - Python Programming

from pathlib import Path

print(Path('/root/file.ext').stem)
Copy The Code & Try With Live Editor

Output

x
+
cmd
file

#4 Code Example with Python Programming

Code - Python Programming

import os

def get_file_name(file_path):
    # Use os.path.basename to get the file name from the file path
    file_name = os.path.basename(file_path)
    return file_name

# Example usage:
file_path = "/path/to/your/file/example.txt"
result = get_file_name(file_path)

print(f"The file name is: {result}")
Copy The Code & Try With Live Editor

Output

x
+
cmd
The file name is: example.txt
Advertisements

Demonstration


Python Programing  to Get the File Name From the File Path-DevsEnv