LoginSignup
0

More than 1 year has passed since last update.

pythonのosモジュールを初めて調べた備忘録

Posted at

osモジュールの概要

OSに依存した機能を利用できる。
主にファイルやディレクトリ操作に用いられる。

使いそうなメソッドだけ備忘録にする。

os.system()でunixコマンドを使う

わざわざ端末を使う必要がなくなる。
cdを使ったディレクトリ移動はできなかった。

os.system("ls")
結果
folder1
a.txt
b.txt
.
.
.

os.get("pwd")とos.getcwd()の結果は同じだった。
なので、unixコマンドで賄える処理はわざわざメソッドを覚えなくてよさそう。

os.path()でファイルの存在確認やパスの取得をする

パス名の取得や分割、結合などの操作ができる。

os.path.join()は引数に与えた2つ以上のパスを結合して返す。str型。

path = os.getcwd()
print(path)

print(os.path.join(path, "abc.txt"))
結果
/home/user/デスクトップ
/home/user/デスクトップ/abc.txt

その他

  • os.mkdir()でパスを引数に与えてディレクトリの作成
  • os.rename()でファイル名の変更
  • os.remove()でファイル削除

参考サイト

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
0