英語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.stat()os.chmod() を使う。

パーミッションを確認する

os.stat() でファイル情報を取得し、st_mode 属性でパーミッションを確認できる。

import os
import stat

mode = os.stat('script.py').st_mode

# 8進数で表示
print(oct(mode))  # 例: 0o100644

# 所有者が実行可能か確認
if mode & stat.S_IXUSR:
    print('所有者は実行可能')

stat モジュールの定数を使うと、特定の権限をチェックできる。

import os
import stat

mode = os.stat('data.txt').st_mode

# 読み取り権限の確認
print('所有者読取:', bool(mode & stat.S_IRUSR))
print('グループ読取:', bool(mode & stat.S_IRGRP))
print('その他読取:', bool(mode & stat.S_IROTH))

# 書き込み権限の確認
print('所有者書込:', bool(mode & stat.S_IWUSR))

パーミッションを変更する

os.chmod() でパーミッションを変更できる。

import os

# 8進数で指定(644 = rw-r--r--)
os.chmod('data.txt', 0o644)

# 実行権限を付与(755 = rwxr-xr-x)
os.chmod('script.py', 0o755)

stat モジュールの定数を使う

stat モジュールの定数を組み合わせると、意図が明確になる。

import os
import stat

# 所有者に読み書き、グループとその他に読み取りのみ
os.chmod('data.txt', stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)

主な定数は以下の通りだ。

定数意味8進数
S_IRUSR所有者読取0o400
S_IWUSR所有者書込0o200
S_IXUSR所有者実行0o100
S_IRGRPグループ読取0o040
S_IWGRPグループ書込0o020
S_IXGRPグループ実行0o010
S_IROTHその他読取0o004
S_IWOTHその他書込0o002
S_IXOTHその他実行0o001

pathlib を使う方法

pathlib でも chmod() メソッドでパーミッションを変更できる。

from pathlib import Path

path = Path('script.py')
path.chmod(0o755)

アクセス可能かどうかを確認する

os.access() を使うと、現在のユーザーがファイルにアクセスできるかを確認できる。

import os

# 読み取り可能か
print(os.access('data.txt', os.R_OK))

# 書き込み可能か
print(os.access('data.txt', os.W_OK))

# 実行可能か
print(os.access('script.py', os.X_OK))