#navi(../)
* Pythonでファイルの有無・ディレクトリの有無を確認する [#ff9dc54a]
Pythonでファイル、ディレクトリの有無をチェックするサンプルコードを以下に記します。

#contents
#htmlinsertpcsp(ll-top.html,ll-sp.html)

* 関連記事 [#s6855b73]
-[[Pythonスクリプトを実行しているパス(ディレクトリ)を取得する>Python/サンプル/スクリプトを実行しているパス(ディレクトリ)を取得する]]
-[[Pythonスクリプトが存在するパス(ディレクトリ)を取得する>Python/サンプル/スクリプトが存在するパス(ディレクトリ)を取得する]]
-[[Pythonのスクリプト名を取得する>Python/サンプル/スクリプト名を取得する]]
-[[Pythonでテキストファイルを1行ずつ読み込む>Python/サンプル/Pythonでテキストファイルを1行ずつ読み込む]]
-[[Pythonでディレクトリを作成・削除する>Python/サンプル/ディレクトリを作成・削除する]]
-[[Pythonでファイルの有無・ディレクトリの有無を確認する>Python/サンプル/ファイルの有無・ディレクトリの有無を確認する]]
-[[Pythonでディレクトリかファイルかどうかを調べる方法>Python/サンプル/ディレクトリかファイルかどうかを調べる方法]]

* 動作環境 [#ta2f1899]
 $ python --version
 Python 2.7.3

 $ lsb_release -d
 Description:    Ubuntu 12.04.4 LTS

* ファイル・ディレクトリの有無を確認する [#s1ba6d11]
ファイルの有無を確認する構文は以下の通りです。
 import os.path
 os.path.exists("ファイルorディレクトリ")
os.path.exists()で有無判定されTrueまたはFalseが返却されます。~
以下にサンプルコードおよび実行出力結果を記します。
-サンプルコード
#ref(exists.py)
 import os.path
 print os.path.exists("/etc")          # directory
 print os.path.exists("/etc/passwd") # file
 
 print os.path.exists("/ETC")          # directory
 print os.path.exists("/etc/hogehoge") # file
-実行結果
 $ python exists.py
 True
 True
 False
 False

ファイルまたはディレクトリが存在すればTrueが返却し存在しない場合はFalseが返却されているのが確認できます。

以上、ファイル・ディレクトリの有無を確認するサンプルコードでした。

#htmlinsertpcsp(ll-btm.html,ll-sp.html)

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS