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 でディレクトリを作成する(mkdir, makedirs)

ディレクトリを作成するには os.mkdir()os.makedirs()、あるいは pathlib.Path.mkdir() を使う。

単一のディレクトリを作成する

os.mkdir() は単一のディレクトリを作成する。

import os

os.mkdir('newdir')

親ディレクトリが存在しない場合はエラーになる。また、すでにディレクトリが存在する場合も FileExistsError が発生する。

中間ディレクトリも含めて作成する

os.makedirs() を使うと、存在しない親ディレクトリも含めて一度に作成できる。

import os

os.makedirs('parent/child/grandchild')

exist_ok=True を指定すると、ディレクトリがすでに存在してもエラーにならない。

import os

os.makedirs('mydir', exist_ok=True)

pathlib を使う方法

pathlib では Path.mkdir() メソッドでディレクトリを作成する。

from pathlib import Path

Path('newdir').mkdir()

parents=True を指定すると親ディレクトリも含めて作成し、exist_ok=True でディレクトリが存在してもエラーにならない。

from pathlib import Path

Path('parent/child/grandchild').mkdir(parents=True, exist_ok=True)

パーミッションを指定する

mode 引数でディレクトリのパーミッションを指定できる。

import os
from pathlib import Path

# os.makedirs
os.makedirs('secure_dir', mode=0o700)

# pathlib
Path('secure_dir').mkdir(mode=0o700)

0o700 は所有者のみが読み書き実行できる設定だ。ただし、実際のパーミッションは umask の影響を受ける。

安全なディレクトリ作成パターン

ディレクトリが存在しない場合のみ作成する一般的なパターンを示す。

from pathlib import Path

def ensure_dir(path):
    """ディレクトリが存在しなければ作成する"""
    Path(path).mkdir(parents=True, exist_ok=True)

# 使用例
ensure_dir('logs/2024/01')

この方法なら、ディレクトリの有無を事前にチェックする必要がない。

一時ディレクトリを作成する

一時的なディレクトリを作成する場合は tempfile モジュールを使うと、自動的に削除される。

import tempfile

with tempfile.TemporaryDirectory() as tmpdir:
    print(tmpdir)  # /tmp/tmpxxxxxx
    # ここで作業
# with を抜けると自動削除