差分
このページの2つのバージョン間の差分を表示します。
| 次のリビジョン | 前のリビジョン | ||
| python:os [2016/10/30 22:49] – 作成 mumeiyamibito | python:os [2019/04/25 11:06] (現在) – [更新日時] mumeiyamibito | ||
|---|---|---|---|
| 行 1: | 行 1: | ||
| - | ====== Python モジュール | + | ====== Python モジュール: os ====== |
| ===== 概要 ===== | ===== 概要 ===== | ||
| + | * ファイルシステムを利用するためのモジュール | ||
| ===== 構文 ===== | ===== 構文 ===== | ||
| * 使うときは\\ <code python> | * 使うときは\\ <code python> | ||
| * 以下ではこの import は省略する | * 以下ではこの import は省略する | ||
| + | * ファイルは hoge.txt を扱うものとする | ||
| ==== ファイルの存在 ==== | ==== ファイルの存在 ==== | ||
| - | * 存在の確認\\ <code python> | + | === 存在の確認 |
| + | <code python> | ||
| if os.path.exists(" | if os.path.exists(" | ||
| print(" | print(" | ||
| 行 14: | 行 16: | ||
| print(" | print(" | ||
| </ | </ | ||
| - | * ファイルであるかの確認\\ <code python> | + | |
| + | === ファイルであるかの確認 | ||
| + | <code python> | ||
| + | if os.path.isfile(" | ||
| + | print(" | ||
| + | else: | ||
| + | print(" | ||
| + | </ | ||
| + | |||
| + | === ディレクトリであるかの確認 === | ||
| + | <code python> | ||
| + | if os.path.isdir(" | ||
| + | print(" | ||
| + | else: | ||
| + | print(" | ||
| + | </ | ||
| + | |||
| + | === リンクであるかの確認 === | ||
| + | <code python> | ||
| + | if os.path.islink(" | ||
| + | print(" | ||
| + | else: | ||
| + | print(" | ||
| + | </ | ||
| + | |||
| + | ==== パーミッション ==== | ||
| + | * パーミッションを取得 (Linux のマスク形式で取得)\\ <code python> | ||
| + | oct(os.stat(" | ||
| + | </ | ||
| + | * 通常の 3 桁の前に '' | ||
| + | * 参考サイト: | ||
| + | * パーミッションの設定 (Linux のマスク形式で設定)\\ <code python> | ||
| + | os.chmod(" | ||
| + | </ | ||
| + | * 今回はパーミッションを 0755 に設定している | ||
| + | * 通常のパーミッションの 3 桁の前に '' | ||
| + | * 参考サイト: | ||
| + | * '' | ||
| + | * 参考サイト: | ||
| + | |||
| + | ==== 更新日時 ==== | ||
| + | * '' | ||
| + | os.stat(FILE).st_atime | ||
| + | os.stat(FILE).st_mtime | ||
| + | os.stat(FILE).st_ctime | ||
| + | </ | ||
| + | * '' | ||
| + | * '' | ||
| + | * '' | ||
| + | * '' | ||
| + | * 得られる日時は UNIX 時間 (1970 年 1 月 1 日 0 時 0 分 0 秒からの時間) なので、datetime モジュールを用いて変換する。\\ <code python> | ||
| + | from datetime import datetime | ||
| + | datetime.fromtimestamp(os.stat(FILE).st_atime).strftime(" | ||
| + | datetime.fromtimestamp(os.stat(FILE).st_mtime).strftime(" | ||
| + | datetime.fromtimestamp(os.stat(FILE).st_ctime).strftime(" | ||
| + | * 参考サイト: | ||
| + | |||
| + | |||
| + | ==== 環境変数取得 ==== | ||
| + | * シェル内部での環境変数を取得する方法\\ <code python> | ||
| + | * '' | ||
| + | * '' | ||
| + | * 例: \\ <code python> | ||
| + | * nautilus-scripts や nemo-scripts の変数も環境変数であるので、この方法で取得する | ||
| + | * 参考サイト: | ||
| + | |||
| + | ==== リンク先を取得 ==== | ||
| + | * [[https:// | ||
| + | |||
| + | {{tag> | ||