124 lines
4.3 KiB
Python
124 lines
4.3 KiB
Python
# check_pkl_files_and_delete.py
|
|
import os
|
|
import pickle
|
|
import numpy as np
|
|
from tqdm import tqdm
|
|
import argparse # 使用 argparse 使其更易于在命令行中使用
|
|
|
|
def check_for_nan_inf(filepath):
|
|
"""
|
|
检查一个 .pkl 文件中的 'data' 字段是否包含 NaN 或 Inf 值。
|
|
|
|
Args:
|
|
filepath (str): .pkl 文件的路径。
|
|
|
|
Returns:
|
|
tuple: (has_nan, has_inf)
|
|
has_nan (bool): 如果 'data' 包含 NaN,则为 True。
|
|
has_inf (bool): 如果 'data' 包含 Inf,则为 True。
|
|
"""
|
|
try:
|
|
with open(filepath, 'rb') as f:
|
|
data_dict = pickle.load(f)
|
|
except Exception:
|
|
# 如果文件无法加载,我们将其视为有问题的文件,但不确定具体问题
|
|
return False, False
|
|
|
|
# 检查 'data' 键是否存在且为 numpy 数组
|
|
if 'data' not in data_dict or not isinstance(data_dict['data'], np.ndarray):
|
|
return False, False
|
|
|
|
sensor_data = data_dict['data']
|
|
|
|
# 核心检查
|
|
has_nan = np.isnan(sensor_data).any()
|
|
has_inf = np.isinf(sensor_data).any()
|
|
|
|
return has_nan, has_inf
|
|
|
|
def main():
|
|
# --- 使用 argparse 来处理命令行参数 ---
|
|
parser = argparse.ArgumentParser(
|
|
description="Scan a directory of .pkl files for NaN/Inf values in the 'data' field and optionally delete them."
|
|
)
|
|
parser.add_argument("directory", type=str, help="The target directory containing .pkl files.")
|
|
parser.add_argument(
|
|
"--delete",
|
|
action="store_true", # 当用户提供 --delete 参数时,这个值为 True
|
|
help="Permanently delete files that contain NaN or Inf values. A confirmation prompt will be shown."
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
target_directory = args.directory
|
|
confirm_delete = args.delete
|
|
|
|
if not os.path.isdir(target_directory):
|
|
print(f"Error: Directory '{target_directory}' not found.")
|
|
return
|
|
|
|
# --- 如果用户选择删除,进行最终确认 ---
|
|
if confirm_delete:
|
|
print("\n!!! WARNING: Files with NaN or Inf values in 'data' will be PERMANENTLY DELETED. !!!")
|
|
final_confirm = input("Are you absolutely sure? This cannot be undone. (yes/no): ").strip().lower()
|
|
if final_confirm != 'yes':
|
|
print("Deletion cancelled by user.")
|
|
confirm_delete = False
|
|
else:
|
|
print("Scan-only mode. Files will NOT be deleted.")
|
|
|
|
print(f"\nScanning directory: {target_directory}")
|
|
|
|
try:
|
|
# 使用 os.scandir 提高效率
|
|
pkl_files = [f.path for f in os.scandir(target_directory) if f.name.endswith(".pkl")]
|
|
except FileNotFoundError:
|
|
print(f"Error: Directory '{target_directory}' not found during scan.")
|
|
return
|
|
|
|
if not pkl_files:
|
|
print("No .pkl files found in the directory.")
|
|
return
|
|
|
|
files_with_nan = []
|
|
files_with_inf = []
|
|
files_deleted_count = 0
|
|
|
|
for pkl_file_path in tqdm(pkl_files, desc="Checking files"):
|
|
has_nan, has_inf = check_for_nan_inf(pkl_file_path)
|
|
|
|
is_problematic = has_nan or has_inf
|
|
|
|
if has_nan:
|
|
files_with_nan.append(os.path.basename(pkl_file_path))
|
|
if has_inf:
|
|
files_with_inf.append(os.path.basename(pkl_file_path))
|
|
|
|
# --- 删除逻辑 ---
|
|
if is_problematic and confirm_delete:
|
|
try:
|
|
os.remove(pkl_file_path)
|
|
files_deleted_count += 1
|
|
except OSError as e:
|
|
print(f"\nERROR: Could not delete file {os.path.basename(pkl_file_path)}: {e}")
|
|
|
|
print("\n--- Scan Complete ---")
|
|
|
|
# --- 报告结果 ---
|
|
if not files_with_nan and not files_with_inf:
|
|
print("✅ All scanned .pkl files are clean (no NaN or Inf values found in 'data').")
|
|
else:
|
|
if files_with_nan:
|
|
print(f"\nFound {len(files_with_nan)} file(s) with NaN values:")
|
|
for fname in files_with_nan:
|
|
print(f" - {fname}")
|
|
|
|
if files_with_inf:
|
|
print(f"\nFound {len(files_with_inf)} file(s) with Inf values:")
|
|
for fname in files_with_inf:
|
|
print(f" - {fname}")
|
|
|
|
if confirm_delete:
|
|
print(f"\nSuccessfully deleted {files_deleted_count} problematic file(s).")
|
|
|
|
if __name__ == "__main__":
|
|
main() |