Computer368106 views
高校倫理1440106 views
高校物理160203 views
数学講師2886227 views
小学算数1200427 views
教育149510 views
高校日本史190571 views
いろは3010814 views
中学英語811710 views
高校化学2924392 views
Help
Tools
NewsSpreadsheetCalendarSlidesTier ListPen ToolIllustrationCrayonPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksWater RippleWater SplashBreaking GlassWood GrainMarble TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsCross SectionsMotion PathMechanicsWavesLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic Theory

English

Python でファイル名から拡張子を除いた部分を取得する(stem, splitext)

ファイル名から拡張子を除いた部分(ベース名)を取得するには os.path.splitext() または pathlib.Path.stem を使う。

import os

path = 'document.pdf'
name, ext = os.path.splitext(path)

print(name)  # document

os.path.splitext() はファイル名を拡張子の前後で分割するため、最初の要素が拡張子を除いた部分になる。

pathlib の stem を使う

pathlib では stem プロパティで直接取得できる。

from pathlib import Path

path = Path('document.pdf')
print(path.stem)  # document

stem は最後の拡張子だけを除くため、.tar.gz のようなファイルでは .tar が残る。

from pathlib import Path

path = Path('archive.tar.gz')
print(path.stem)  # archive.tar

すべての拡張子を除く

複数の拡張子をすべて除きたい場合は、stem を繰り返し適用するか、拡張子がなくなるまでループする。

from pathlib import Path

path = Path('archive.tar.gz')

while path.suffix:
    path = Path(path.stem)

print(path)  # archive

または suffixes の長さ分だけ処理する方法もある。

from pathlib import Path

path = Path('archive.tar.gz')
name = path.name

for suffix in path.suffixes:
    name = name.removesuffix(suffix)

print(name)  # archive

ディレクトリパスからファイル名部分を取得する

フルパスからファイル名部分だけを取得するには os.path.basename() または Path.name を使う。

import os
from pathlib import Path

full_path = '/home/user/documents/report.pdf'

# os.path
print(os.path.basename(full_path))  # report.pdf

# pathlib
print(Path(full_path).name)  # report.pdf

ファイル名から拡張子を除くには、これを splitext()stem と組み合わせる。

import os
from pathlib import Path

full_path = '/home/user/documents/report.pdf'

# os.path
basename = os.path.basename(full_path)
name = os.path.splitext(basename)[0]
print(name)  # report

# pathlib
print(Path(full_path).stem)  # report

pathlib の方が簡潔に書けることがわかる。