本站以分享各种运维经验和运维所需要的技能为主
《python零基础入门》:python零基础入门学习
《python运维脚本》...
《shell》:shell学习
《terraform》持续更新中:terraform_Aws学习零基础入门到最佳实战
《k8》暂未更新
《docker学习》暂未更新
《ceph学习》ceph日常问题解决分享
《日志收集》ELK+各种中间件
《运维日常》持续更新中
使用Python编写的多线程快速批量删除文件的脚本
以下是使用Python编写的多线程快速批量删除文件的脚本示例:
import os
import threading
def delete_files(file_list):
for file_path in file_list:
try:
os.remove(file_path)
print(f"Deleted file: {file_path}")
except OSError as e:
print(f"Error deleting file: {file_path} - {e}")
def batch_delete_files(directory, file_extension):
file_list = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(file_extension):
file_path = os.path.join(root, file)
file_list.append(file_path)
# 设置线程数,根据需要进行调整
num_threads = 4
# 每个线程处理的文件数量
files_per_thread = len(file_list) // num_threads
# 创建线程列表
threads = []
for i in range(num_threads):
start_index = i * files_per_thread
end_index = start_index + files_per_thread if i < num_threads - 1 else len(file_list)
thread_files = file_list[start_index:end_index]
thread = threading.Thread(target=delete_files, args=(thread_files,))
threads.append(thread)
# 启动线程
for thread in threads:
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
print("All files deleted.")
# 示例用法
directory = "/path/to/directory" # 要删除文件的目录
file_extension = ".txt" # 要删除的文件扩展名
batch_delete_files(directory, file_extension)
让我们一起实践学习更多有用python脚本。