How to get file name without extension in python with example
This tutorial shows how to get file names and extensions in Python
- Get the File name
- Get File name without extension
- Get File extension in Python
Python to get File name without extension
- use os.path.basename function
- Takes the path of a file including the directory
- It returns the file name with an extension
- use the
os.path.splitext
function to split into name and extension, - Returns array of strings, first element name, second element is an extension
import os
path=os.path.basename('a:\data.txt')
print(path) # data.txt
print(os.path.splitext(path)) # ('data', '.txt')
print(os.path.splitext(path)[0]) # data
print(os.path.splitext(path)[1]) # .txt
use pathlib🔗 Path function
pathlib
contains stem returns file name without extension. It works from Python 3.4 onwards.stem returns the file name without extension
name: returns file name with extension
suffix: returns the file extension with
.
includedsuffixes: contains an array of suffixes.
Here is an example
from pathlib import Path
path=Path("a:\data.txt")
print(path.resolve().stem) # data
print(path.name) # data.txt
print(path.suffix) # .txt
print(path.suffixes) # ['.txt']