6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pathlib マイチートシート

Last updated at Posted at 2018-10-28

OSコマンドとpathlibの対比を整理する。

from pathlib import Path
from stat import filemode
from shutil import rmtree

p_new_file = Path('./new_file.txt')
p = Path('.')

OSコマンド pathlib
touch p_new_file.touch()
rm p_new_file.unlink()
chmod 755 p_new_file.chmod(0o755) # 8進数で指定
ls -la # 権限確認 filemode( p_new_file.stat().st_mode)
ls -la # owner確認 p_new_file.owner()
ls -la # group確認 p_new_file.group()
ls -la # 存在確認 p_new_file.exists()
ls -la # ファイル確認 p_new_file.id_file()
ls -la # ディレクトリ確認 p_new_file.is_dir()
ls -lF (grep -v \) # ファイルだけ [x for x in p.iterdir() if x.is_file()] # ファイル一覧
ls -lF (grep \) # ディレクトリだけ [x for x in p.iterdir() if x.is_dir()] # ディレクトリ一覧
pwd p.cwd()
mkdir p.mkdir()
mkdir -p p.mkdir(parents=True)
rm -fr rmtree(p)

固有の話

やりたいこと pathlib
絶対パス変換 p_new_file.resolve()
パス連結 p_new_file / 'sub_dir' / 'file2.txt
ファイル名 p_new_file.name
絶対パスか判定 p_new_file.is_absolute()
親ディレクトリ p_new_file.resolve().parent
拡張子取得 p_new_file.resolve().suffix
同じディレクトリに別名ファイルを作る p_new_file.with_name('file_new.txt')
パターン検索 p.glob('**/*.txt')
ファイル削除 内包 [p.unlink() for p in p_temp.glob('**/*') if re.search('\d+.txt', str(p)) and p.is_file()]
ファイルのopen with p_new_file.open(mode='w') as f:
ファイルの読み込み # ファイルのopenの後で f.read() # ファイル全体を文字列として読み込み
f.readlines() # ファイル全体をリストとして読み込み
f.readline() # ファイルを一行づつ読み込み
6
9
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
6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?