92 lines
3.5 KiB
Python
92 lines
3.5 KiB
Python
import pickle
|
|
import os
|
|
|
|
|
|
def split_pkl_file(input_file, output_dir, original_filename_base):
|
|
"""
|
|
将包含字典列表的单个pkl文件分割成多个pkl文件,并保存到指定的单个目录中。
|
|
|
|
参数:
|
|
input_file (str): 输入的pkl文件路径。
|
|
output_dir (str): 所有分割后文件存放的输出目录路径。
|
|
original_filename_base (str): 原始文件名(不含扩展名),用于生成新文件名。
|
|
"""
|
|
# 加载原始pkl文件
|
|
try:
|
|
with open(input_file, 'rb') as f:
|
|
data_list = pickle.load(f)
|
|
except (pickle.UnpicklingError, EOFError) as e:
|
|
print(f"错误: 无法加载或解析文件 {input_file}。跳过。错误信息: {e}")
|
|
return 0 # 返回处理的项目数
|
|
|
|
# 检查输入数据是否是列表
|
|
if not isinstance(data_list, list):
|
|
print(f"警告: 输入文件 {input_file} 不包含列表,跳过。")
|
|
return 0
|
|
|
|
# 遍历列表中的每个字典并保存为单独的pkl文件
|
|
count = 0
|
|
for i, item in enumerate(data_list):
|
|
if not isinstance(item, dict):
|
|
print(f"警告: 文件 {input_file} 中第 {i} 项不是字典,跳过。")
|
|
continue
|
|
|
|
# 使用 "原文件名_序号.pkl" 的格式创建新文件名
|
|
output_filename = f'{original_filename_base}_item_{i}.pkl'
|
|
output_file_path = os.path.join(output_dir, output_filename)
|
|
|
|
with open(output_file_path, 'wb') as f:
|
|
pickle.dump(item, f)
|
|
count += 1
|
|
|
|
print(f"从 {os.path.basename(input_file)} 中成功分割 {count} 个项目到 {output_dir} 目录。")
|
|
return count
|
|
|
|
|
|
def process_directory(input_dir, output_dir):
|
|
"""
|
|
处理输入目录下的所有pkl文件,将它们分割后的所有独立项保存到同一个输出目录中。
|
|
|
|
参数:
|
|
input_dir (str): 输入的目录路径,包含多个pkl文件。
|
|
output_dir (str): 统一的输出目录路径。
|
|
"""
|
|
# 检查输入目录是否存在
|
|
if not os.path.isdir(input_dir):
|
|
raise ValueError(f"输入路径 {input_dir} 不是一个有效的目录。")
|
|
|
|
# 确保输出目录存在
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
|
|
total_items_processed = 0
|
|
|
|
# 遍历输入目录下的所有文件
|
|
file_list = sorted(os.listdir(input_dir)) # 排序以保证处理顺序一致
|
|
for filename in file_list:
|
|
if filename.endswith('.pkl'):
|
|
input_file_path = os.path.join(input_dir, filename)
|
|
|
|
# 获取不带扩展名的原始文件名,用于命名输出文件
|
|
original_filename_base = os.path.splitext(filename)[0]
|
|
|
|
try:
|
|
# 调用分割函数,传入统一的输出目录和原始文件名
|
|
num_items = split_pkl_file(
|
|
input_file_path, output_dir, original_filename_base)
|
|
total_items_processed += num_items
|
|
except Exception as e:
|
|
print(f"处理文件 {input_file_path} 时发生严重错误: {str(e)}")
|
|
|
|
print(f"\n处理完成!总共处理了 {total_items_processed} 个项目,并保存到目录: {output_dir}")
|
|
|
|
|
|
# --- 使用示例 ---
|
|
if __name__ == "__main__":
|
|
# 设置输入和输出目录
|
|
input_directory = r"/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/full_data" # 替换为你的输入目录路径
|
|
# 替换为你想要的统一输出目录
|
|
output_directory = r"/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/temp"
|
|
|
|
# 执行处理
|
|
process_directory(input_directory, output_directory)
|