[Python]ファイルやディレクトリの存在を確認する
osモジュールのpath.exists関数を使う。path.exists関数は引数に与えたパスがファイルでもディレクトリでも存在していればTrueを返す。
ファイルかディレクトリの判定はpath.isfile関数かpath.isdir関数を使う。この両関数は、存在しないパスを指定するとFalseを返す。
>>> import os
>>> os.path.exists('C:\Windows\write.exe')
True
>>> os.path.exists('C:\Windows')
True
>>> os.path.exists('C:\Windows\write.ex')
False
>>> os.path.exists('C:\Win')
False
>>> os.path.isfile('C:\Windows\write.exe')
True
>>> os.path.isdir('C:\Windows\write.exe')
False
>>> os.path.isfile('C:\Windows')
False
>>> os.path.isdir('C:\Windows')
True
>>> os.path.isfile('C:\Win')
False
>>> os.path.isdir('C:\Win')
False
« [Python]リストのリスト(2次元配列)を作る | トップページ | [Visual Basic]正規表現を使って文字列を分割する »
「Python」カテゴリの記事
- [Python]コマンドラインでバージョンを確認する(2025.02.06)
- [Python]文字列のハッシュ値を得る(2025.02.03)
- [Python]等差数列を作成する(2023.06.05)
- [Python]連立一次方程式を解く(2023.04.26)
- [Python]ファイルのハッシュ値を得る(2023.04.15)
« [Python]リストのリスト(2次元配列)を作る | トップページ | [Visual Basic]正規表現を使って文字列を分割する »

コメント