2021-08-03に投稿

Python 標準ライブラリ shutil ファイル操作

このライブラリを使うことでファイルの移動やコピーを行える。

ファイルコピーを行う関数

# copyfileobj(fsrc, fdst[, length]) ファイルオブジェクトでコピー
with open("./test/sample.txt", mode="r") as fsrc, open('./test/sample_copy.txt', mode="w") as fdst:
    shutil.copyfileobj(fsrc, fdst)

# copyfile(src, dst, *, follow_symlinks=True) ファイルコピー(メタデータ含まない)
shutil.copyfile("./test/sample.txt", "./test/sample_copy.txt")

# copymode(src, dst, *, follow_symlinks=True) パーミッションコピー
shutil.copymode("./test/sample.txt", "./test/sample_copy.txt")

# copystat(src, dst, *, follow_symlinks=True) メタデータコピー
shutil.copystat("./test/sample.txt", "./test/sample_copy.txt")

# copy(src, dst, *, follow_symlinks=True) ファイルまたはディレクトリへのコピー
shutil.copy("./test/sample.txt", "./test/sample_copy.txt") # => './test/sample_copy.txt' にコピー
shutil.copy("./test/sample.txt", "./test/A") # => './test/A/sample.txt' にコピー

# copy2(src, dst, *, follow_symlinks=True) ファイルまたはディレクトリへのコピー(メタデータあり)
shutil.copy2("./test/sample.txt", "./test/sample_copy.txt") # => './test/sample_copy.txt' にコピー
shutil.copy2("./test/sample.txt", "./test/A") # => './test/A/sample.txt' にコピー

ディレクトリのコピー

# copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)
shutil.copytree("./test/A", "./test/C") 

ディレクトリを削除

# rmtree(path, ignore_errors=False, onerror=None)
shutil.rmtree("./test/C")

ファイル・ディレクトリ移動

# move(src, dst, copy_function=copy2)
shutil.move("./test/sample.txt", "./test/sample_move.txt")
shutil.move("./test/B", "./test/B_Moved")

ファイル・ディレクトリ情報

# disk_usage(path) ディスク使用状況
shutil.disk_usage("./test/A") # => usage(total=1022878543872, used=512685293568, free=510193250304)
shutil.disk_usage(r"C:\\") # => usage(total=1022878543872, used=512687771648, free=510190772224)

# which(cmd, mode=os.F_OK | os.X_OK, path=None) 実行パスの取得
shutil.which("notepad.exe") # => 'C:\\windows\\system32\\notepad.exe'

圧縮・解凍

圧縮をサポートしているフォーマット

shutil.get_archive_formats()
[('bztar', "bzip2'ed tar-file"),
 ('gztar', "gzip'ed tar-file"),
 ('tar', 'uncompressed tar file'),
 ('xztar', "xz'ed tar-file"),
 ('zip', 'ZIP file')]

圧縮・アーカイブ化

make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])

shutil.make_archive("./out/archives","zip","./test/A")

解凍をサポートしているフォーマット

shutil.get_unpack_formats()
[('bztar', ['.tar.bz2', '.tbz2'], "bzip2'ed tar-file"),
 ('gztar', ['.tar.gz', '.tgz'], "gzip'ed tar-file"),
 ('tar', ['.tar'], 'uncompressed tar file'),
 ('xztar', ['.tar.xz', '.txz'], "xz'ed tar-file"),
 ('zip', ['.zip'], 'ZIP file')]

解凍

unpack_archive(filename[, extract_dir[, format]])

shutil.unpack_archive("./out/archives.zip", "./extract_dir")
Originally published at marusankakusikaku.jp
ツイッターでシェア
みんなに共有、忘れないようにメモ

maru3kaku4kaku

Pythonこつこつ学習中。よく忘れる。

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント