Pythonのshutilモジュールにおける用法

shutilモジュールはPython標準ライブラリ内の、高度なファイル、フォルダ操作用モジュールです。以下は、shutilモジュールの一般的な使用例です。

  1. ファイルまたはフォルダーをコピーします。
import shutil

# 复制文件
shutil.copy('source_file.txt', 'destination_folder')

# 复制文件夹及其内容
shutil.copytree('source_folder', 'destination_folder')
  1. ファイルを移動またはフォルダーを移動する:
import shutil

# 移动文件
shutil.move('source_file.txt', 'destination_folder')

# 移动文件夹及其内容
shutil.move('source_folder', 'destination_folder')
  1. ファイルを削除またはフォルダを削除する:
import shutil

# 删除文件
shutil.remove('file.txt')

# 删除文件夹及其内容
shutil.rmtree('folder')
  1. ファイルまたはフォルダの名前を変更する:
import shutil

# 重命名文件
shutil.move('old_file.txt', 'new_file.txt')

# 重命名文件夹
shutil.move('old_folder', 'new_folder')
  1. ファイルを圧縮する
import shutil

# 压缩文件夹
shutil.make_archive('archive', 'zip', 'folder')

# 解压缩文件
shutil.unpack_archive('archive.zip', 'destination_folder')

shutilモジュールを使用する場合に注意すべきなのは、宛先ファイルまたはフォルダーのパスが存在していないとエラーになる可能性があることです。

bannerAds