2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python osモジュールまとめ

Posted at

(この記事はChatGPT4oにより生成されました。)

Python の os モジュールは、オペレーティングシステム(OS)に依存した機能を使うための標準ライブラリです。ファイルやディレクトリの操作、環境変数の取得・設定、パスの扱いなどが可能です。ここでは、よく使う機能をざっとまとめます。


1. 基本的な使い方

import os

os モジュールをインポートすることで使用可能になります。


2. カレントディレクトリの操作

  • 現在のディレクトリ取得
cwd = os.getcwd()
print(cwd)
  • ディレクトリ移動
os.chdir('/path/to/dir')

3. ファイル・ディレクトリの一覧取得

files = os.listdir('.')
print(files)

. はカレントディレクトリを指します。


4. ファイル・ディレクトリの作成と削除

  • ディレクトリ作成
os.mkdir('new_folder')
  • ディレクトリの再帰的作成(中間ディレクトリごと)
os.makedirs('parent/child/grandchild')
  • ディレクトリ削除
os.rmdir('new_folder')
  • ファイル削除
os.remove('file.txt')

5. パス操作(os.path サブモジュール)

  • パスの結合
path = os.path.join('folder', 'file.txt')
  • 絶対パスに変換
abs_path = os.path.abspath('file.txt')
  • パスが存在するか確認
os.path.exists('file.txt')  # True or False
  • ファイルかディレクトリか確認
os.path.isfile('file.txt')
os.path.isdir('folder')
  • パスの分解
dirname = os.path.dirname('/path/to/file.txt')  # '/path/to'
basename = os.path.basename('/path/to/file.txt')  # 'file.txt'

6. 環境変数の操作

env_path = os.environ.get('PATH')  # 取得
os.environ['MY_ENV'] = '123'       # 設定

7. システムコマンドの実行

os.system('ls -l')  # Linux/macOS

subprocess モジュールの使用が推奨される場合が多い。


8. ファイル情報取得

info = os.stat('file.txt')
print(info.st_size)  # ファイルサイズ(バイト)

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?