1: 2016-12-29 (木) 06:53:58 njf |
現: 2016-12-30 (金) 12:19:29 njf |
- | *始めに [#t8e9a620] | + | Pythonではファイルやディレクトリの存在チェックや削除など、主なファイル操作が一通りできるようになっています。 |
| | | |
- | *ファイルの存在チェック [#ebaf880c] | + | ただ、ファイル操作が中心ならshellを使った方が簡単なことが多いので、無理になにもかもPythonを使うより組み合わせたりするのがおすすめです。 |
| | | |
- | *ファイルの読み込み [#s7074ae0] | + | *ファイルやディレクトリの存在チェック [#ebaf880c] |
| | | |
- | *ファイルの書き込み [#w45d2a77] | + | **ファイルとディレクトリを区別しない存在チェック [#ycc2a67a] |
| + | ファイルまたはディレクトリを区別しない存在チェックには「os.path.exists」を使います。 |
| + | ファイル、ディレクトリ(フォルダ)どちらにも適用できて、相対パス、絶対パスどちらでも可能です。 |
| + | |
| + | import os |
| + | if os.path.exists("../"): |
| + | print "exist!" |
| + | else: |
| + | print "not exist" |
| + | |
| + | 結果 |
| + | exist! |
| + | |
| + | 「../」は自分自身の実行されているディレクトリを指すので、必ず存在します。このようにファイルやディレクトリが存在すると、真を返します。 |
| + | |
| + | **ファイルとディレクトリを区別する存在チェック [#k44389ea] |
| + | 存在してかつファイルかどうかまで判定するには「os.path.isfile」、ディレクトリかどうかは「os.path.isdir」を使います。 |
| + | |
| + | 使い方は「os.path.exists」と全く同じです。 |
| + | if os.path.isdir("../"): |
| + | print "dir!" |
| + | else: |
| + | print "not dir" |
| + | |
| + | |
| + | if os.path.isfile("../"): |
| + | print "file!" |
| + | else: |
| + | print "not file" |
| + | |
| + | 結果 |
| + | |
| + | dir! |
| + | not file |
| + | |
| + | *ディレクトリの作成 [#lc17f921] |
| + | |
| + | ディレクトリを作成するには「os.mkdir」を使います。 |
| + | |
| + | import os |
| + | |
| + | os.mkdir("test_dir") |
| + | |
| + | すでに存在するとエラーになるので、たいてい前節のディレクトリの存在チェックとあわせて使うことになります。 |
| + | |
| + | *ディレクトリの削除 [#red41cd3] |
| + | |
| + | ディレクトリが空なら「os.rmdir」を使います。 |
| + | |
| + | os.rmdir("test_dir") |
| + | |
| + | 空では無く、中身も一緒に消したいときは「shutil.rmtree」を使います。 |
| + | import shutil |
| + | shutil.rmtree("test_dir") |
| + | |
| + | *ファイルの削除 [#f675df31] |
| + | |
| + | ファイルを削除するには「os.remove」を使います。 |
| + | |
| + | os.remove("test.txt") |
| + | |
| + | *ファイルの移動 [#lf3238e2] |
| + | ファイルを移動するには「shutil.move」を使います。 |
| + | shutil.move("test1.txt","test2.txt") |
| + | |
| + | *ファイル、ディレクトリの名前の変更 [#tce0a934] |
| + | ファイルなどの名前変更は「os.rename」を使います。 |
| + | os.rename("test1.txt","test2.txt") |
| + | |
| + | *ファイル一覧の取得 [#r9a82e36] |
| + | |
| + | 指定したディレクトリの中のファイル一覧を取得するには、「os.listdir」を使います。 |
| + | |
| + | files = os.listdir('./') |
| + | |
| + | for f in files: |
| + | print f |
| + | |
| + | ワイルドカードを使うには「glob.glob」を使います。 |
| + | |
| + | import glob |
| + | files = glob.glob('./*.py') |
| + | |
| + | for f in files: |
| + | print f |