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 でファイルを削除・移動・コピーする(shutil)

ファイルの削除・移動・コピーには os モジュールと shutil モジュールを使う。

ファイルを削除する

ファイルの削除には os.remove() を使う。

import os

os.remove('data.txt')

存在しないファイルを削除しようとすると FileNotFoundError が発生するため、事前に存在確認をするか例外処理を行う。

import os

path = 'data.txt'
if os.path.exists(path):
    os.remove(path)

ディレクトリを削除する

空のディレクトリは os.rmdir() で削除できる。中身があるディレクトリを丸ごと削除するには shutil.rmtree() を使う。

import os
import shutil

# 空のディレクトリを削除
os.rmdir('empty_dir')

# 中身ごとディレクトリを削除
shutil.rmtree('mydir')

shutil.rmtree() は強力なので、誤って重要なディレクトリを削除しないよう注意が必要だ。

ファイルを移動する

ファイルの移動には shutil.move() を使う。

import shutil

shutil.move('data.txt', 'backup/data.txt')

移動先にファイル名を含めれば名前を変更しながら移動できる。移動先がディレクトリ名だけなら、元のファイル名で移動される。

ファイルをコピーする

ファイルのコピーには shutil.copy() または shutil.copy2() を使う。

import shutil

# メタデータをコピーしない
shutil.copy('data.txt', 'data_backup.txt')

# メタデータ(更新日時など)も含めてコピー
shutil.copy2('data.txt', 'data_backup.txt')

shutil.copy() はファイルの内容とパーミッションをコピーする。shutil.copy2() はそれに加えて更新日時などのメタデータもコピーする。

ディレクトリをコピーする

ディレクトリを丸ごとコピーするには shutil.copytree() を使う。

import shutil

shutil.copytree('mydir', 'mydir_backup')

コピー先のディレクトリがすでに存在するとエラーになる。Python 3.8 以降では dirs_exist_ok=True を指定すると、既存ディレクトリにマージできる。