英語613639 views
数学講師2886227 views
世界の国564520 views
高校物理160203 views
中学英語811710 views
中学社会668760 views
高校国語788336 views
高校化学2924392 views
LaTeX962153 views
Computer368106 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 でファイルの拡張子を取得・変更する

ファイルパスから拡張子を取得するには os.path.splitext() または pathlib.Path.suffix を使う。

import os

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

print(name)  # document
print(ext)   # .pdf

os.path.splitext() はファイル名を「拡張子より前」と「拡張子」に分割する。拡張子にはドットが含まれる。

pathlib を使う方法

pathlib では suffix プロパティで拡張子を取得できる。

from pathlib import Path

path = Path('document.pdf')

print(path.suffix)   # .pdf
print(path.stem)     # document

.tar.gz のような複数の拡張子を持つファイルでは、suffix は最後の .gz だけを返す。すべての拡張子を取得するには suffixes を使う。

from pathlib import Path

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

print(path.suffix)    # .gz
print(path.suffixes)  # ['.tar', '.gz']

拡張子を変更する

pathlibwith_suffix() メソッドを使うと、拡張子を変更した新しいパスを取得できる。

from pathlib import Path

path = Path('document.txt')
new_path = path.with_suffix('.md')

print(new_path)  # document.md

元のファイルが変更されるわけではなく、新しい Path オブジェクトが返される。実際にファイル名を変更するには rename() と組み合わせる。

from pathlib import Path

path = Path('document.txt')
path.rename(path.with_suffix('.md'))

拡張子を削除する

拡張子を削除するには with_suffix('') で空文字を指定する。

from pathlib import Path

path = Path('document.txt')
print(path.with_suffix(''))  # document