Pythonでフォルダー内のすべてのファイルを削除する方法は?
os モジュールの listdir 関数を使用してフォルダー内のすべてのファイル名を取得し、os.remove 関数を使用して各ファイルを削除することができます。以下は一例です:
import os
def delete_files_in_folder(folder):
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
delete_files_in_folder(file_path)
os.rmdir(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
folder_path = '/path/to/folder'
delete_files_in_folder(folder_path)
この例では、delete_files_in_folder関数はフォルダのパスを引数として受け取り、フォルダ内のすべてのファイルとサブフォルダを処理します。ファイルまたはシンボリックリンクの場合、os.unlink関数を使用してファイルを削除します。フォルダの場合、delete_files_in_folder関数を再帰的に呼び出してサブフォルダ内のすべてのファイルを削除し、os.rmdir関数を使用してフォルダ自体を削除します。