💻
Code Snippet
  • Overview
  • General
    • Anaconda
  • GUI
    • PyQT
      • Qt Design
  • Pandas
    • Read Data
    • Replace
  • Articles
    • Python. PyQt
    • Offline Payment Wallet With Django
    • Documentation Encrypt File
    • Play With Pillow
  • Fontend
    • Snippet
    • Hugo
    • JavaScript
      • Form Validation
  • Finance
    • Library
      • yfinance
  • Notebook
    • Untitled
    • Snippet
  • Python
    • Download file
    • Date and Time
    • Snippet
    • Compile .exe
    • Overview
    • Google
      • Samples for Google Workspace
      • Drive
      • GoogleSheet
    • Virtual environment
    • Database
      • Pickle()
    • Datatypes
      • Excel
      • Dictionary
        • xmltodict()
    • File Handling
      • shutil()
      • Get the File Name
      • Get the Full Path
      • Check the File Size
      • Get File Creation Date
      • Find All File
        • Untitled
    • Dictionary
      • Convert Two Lists
  • Data Science
    • HTTP requests
  • Google Workspace
    • Overview
    • Apps Script
      • ์Note
      • Overview
      • Snippet
        • HTML Service
        • Fetch API
      • Quickstart
      • Google Sheets
        • Overview
          • Snippet
        • Fundamentals
          • Macros & Custom Functions
          • Spreadsheets, Sheets, and Ranges
          • Working with Data
          • Data Formatting
          • Chart and Present Data
        • Built-in Google Services
        • Fetch and format API data
        • Connected Sheets
  • Git
  • Mini Lab
    • Line
    • Python
  • Function
    • Python
      • Date&Time
  • Database
    • SQLite
      • Example
Powered by GitBook
On this page
  • Get the File Name From the File Path
  • Example 1: Using os module
  • Example 2: Using Path module

Was this helpful?

  1. Python
  2. File Handling

Get the File Name

Previousshutil()NextGet the Full Path

Last updated 3 years ago

Was this helpful?

Get the File Name From the File Path

In this example, you will learn to get the file name from the file path.

To understand this example, you should have the knowledge of the following topics:

Example 1: Using os module

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])

Output

file

basename() gives the name of the last file/folder of the path, whereas splitext() splits the file name into filename and extension.

import os

print(os.path.splitext(file_name)[0])

Output

('file', '.ext')

Example 2: Using Path module

from pathlib import Path

print(Path('/root/file.ext').stem)

Output

file

It works for python 3.4 and above.

https://www.programiz.com/python-programming/examples/file-name-from-file-path
Python programming
Python File I/O
Python Strings