Home >Backend Development >Python Tutorial >How Can I Extract Filenames Without Extensions in Python?

How Can I Extract Filenames Without Extensions in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 01:17:15484browse

How Can I Extract Filenames Without Extensions in Python?

Extracting Filenames Without Extensions from Paths in Python

Retrieving the filename of a path without its corresponding extension is a common task in programming. Python offers multiple approaches to accomplish this, especially since different versions of Python have varying methods.

Python 3.4 and Above


1. pathlib.Path.stem

In Python 3.4 and subsequent versions, utilizing pathlib.Path.stem allows for the straightforward extraction of filenames without extensions.

from pathlib import Path

path = "/Users/Documents/Desktop/test.pdf"

filename = Path(path).stem

print(filename)  # output: test

Python Versions Prior to 3.4


1. os.path.splitext and os.path.basename Combination

Before Python 3.4, combining os.path.splitext and os.path.basename provides a viable solution.

import os.path

path = "C:\Documents\MyFile.docx"

filename = os.path.splitext(os.path.basename(path))[0]

print(filename)  # output: MyFile
Example Usage:
for path in ["/home/user/myfile.txt", "/path/to/my_file.py"]:
    filename = Path(path).stem if sys.version_info >= (3, 4) else os.path.splitext(os.path.basename(path))[0]
    print(filename)  # output: [('myfile', '.txt'), ('my_file', '.py')]

The above is the detailed content of How Can I Extract Filenames Without Extensions in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn