高校物理160203 views
高校倫理1440106 views
中学理科1630641 views
英語613639 views
小学算数1200427 views
ヒストリア290598 views
中学英語811710 views
Computer368106 views
高校日本史190571 views
世界の国564520 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.exists, pathlib)

ファイルやディレクトリが存在するかどうかを確認するには os.path.exists() または pathlib.Path.exists() を使う。

import os

# ファイルの存在確認
if os.path.exists('data.txt'):
    print('ファイルが存在します')

# ディレクトリの存在確認
if os.path.exists('mydir'):
    print('ディレクトリが存在します')

os.path.exists() はファイルでもディレクトリでも存在すれば True を返す。ファイルかディレクトリかを区別したい場合は os.path.isfile()os.path.isdir() を使う。

import os

path = 'data.txt'

if os.path.isfile(path):
    print('ファイルです')
elif os.path.isdir(path):
    print('ディレクトリです')
else:
    print('存在しません')

pathlib を使う方法

Python 3.4 以降では pathlib モジュールを使ったオブジェクト指向的な書き方もできる。

from pathlib import Path

path = Path('data.txt')

if path.exists():
    print('存在します')

if path.is_file():
    print('ファイルです')

if path.is_dir():
    print('ディレクトリです')

pathlib はパス操作をメソッドチェーンで書けるため、複雑なパス処理では可読性が高くなる。

シンボリックリンクの扱い

exists() はシンボリックリンクをたどって、リンク先が存在するかどうかを確認する。リンク自体の存在を確認したい場合は os.path.lexists() または Path.is_symlink() を使う。

import os
from pathlib import Path

# シンボリックリンク自体の存在確認
os.path.lexists('mylink')

# pathlib でシンボリックリンクかどうかを確認
Path('mylink').is_symlink()