一:表格过度配置,表格资源是否在工程中存在,并输出不存在的资源
import pandas as pd
import glob
import os
assets = []
count = 0
for file_path in glob.glob('configs/*.xlsx'):
count += 1
try:
sheets = pd.read_excel(file_path, sheet_name=None)
except Exception as e:
print(f"读取文件 {file_path} 时出错:{e}")
continue
for sheet_name, df in sheets.items():
print('正在读取文件:', file_path, 'sheet:', sheet_name)
all_values = df.values.ravel()
for value in all_values:
if isinstance(value, str) and value.startswith('Assets/'):
assets.append(value)
output_path = "output.xlsx"
if os.path.exists(output_path):
os.remove(output_path)
if assets:
df_output = pd.DataFrame(assets, columns=["Asset Path"])
df_output.to_excel(output_path, index=False)
print(f"\n结果已写入 {output_path}")
else:
print("\n未找到以'Assets/'开头的内容")
not_exist_assets = []
for asset_path in assets:
full_path = os.path.join('../MainProject', asset_path)
if not os.path.exists(full_path):
not_exist_assets.append(asset_path)
not_exist_output = "FileNotExist.xlsx"
if not_exist_assets:
if os.path.exists(not_exist_output):
os.remove(not_exist_output)
df_not_exist = pd.DataFrame(not_exist_assets, columns=["Asset Path"])
df_not_exist.to_excel(not_exist_output, index=False)
print(f"\n以下资源文件不存在,已写入 {not_exist_output}:")
for path in not_exist_assets:
print(path)
else:
print("\n所有资源文件均存在。")
print("\n匹配的内容列表:")
for item in assets:
print(item)
print("\n一共读取了", count, "个文件,匹配到", len(assets), "条有效数据")
二:收集打包目录
import os
file_paths = [
r'..\MainProject\Assets\Build\AssetBundle\AssetBundleConfig.asset',
r'..\MainProject\Assets\Build\AssetBundle\SegmentedUpdateConfig.asset'
]
keys = []
for file_path in file_paths:
try:
with open(file_path, 'r', encoding='utf-8') as file:
print(f"\n{'='*50}")
print(f"正在读取文件:{os.path.abspath(file_path)}")
print("-" * 50)
file_keys = []
for line_number, line in enumerate(file, 1):
formatted_line = line.strip()
if "Assets/" in formatted_line:
cleaned_key = formatted_line.replace("- ", "")
file_keys.append(cleaned_key)
print(f"[Line {line_number:03d}] 发现有效键 | 原始内容:{formatted_line} | 处理后:{cleaned_key}")
else:
print(f"[Line {line_number:03d}] {formatted_line}")
keys.extend(file_keys)
print(f"\n当前文件提取到 {len(file_keys)} 个有效键")
except FileNotFoundError:
print(f"错误:文件不存在 {os.path.abspath(file_path)}")
except PermissionError:
print(f"错误:没有权限读取文件 {file_path}")
except UnicodeDecodeError:
print(f"错误:文件编码格式不支持,尝试使用其他编码(如utf-16)")
except Exception as e:
print(f"发生未知错误:{str(e)}")
else:
print("-" * 50)
print(f"文件 {os.path.basename(file_path)} 处理完成")
print("\n" + "="*50)
print(f"共处理 {len(file_paths)} 个文件,总计提取到 {len(keys)} 个有效键:")
for i, key in enumerate(keys, 1):
print(f"{i:03d}. {key}")
三:是否进包,资源是否存在打包目录
import pandas as pd
import glob
import os
from datetime import datetime
def clean_old_files():
"""清理历史文件"""
target_files = ['keys.txt', '异常资源报告.xlsx']
for file in target_files:
try:
os.remove(file)
print(f" ▹ 已删除旧文件:{file}")
except FileNotFoundError:
pass
except Exception as e:
print(f"‼️ 文件删除异常:{file}")
print(f"错误详情:{str(e)}")
def collect_assets():
"""从Excel文件收集资源路径"""
assets = []
file_count = 0
print(f"\n{'='*50}")
print("开始扫描Excel配置文件")
print(f"扫描时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
for file_path in glob.glob('configs/*.xlsx'):
file_count += 1
try:
sheets = pd.read_excel(file_path, sheet_name=None)
filename = os.path.basename(file_path)
print(f"\n▸ 正在处理:{filename}")
for sheet_name, df in sheets.items():
print(f" ├─ 工作表:{sheet_name}")
all_values = df.values.ravel()
for value in all_values:
if isinstance(value, str) and value.startswith('Assets/'):
assets.append({
'file': filename,
'sheet': sheet_name,
'path': value
})
except Exception as e:
print(f"\n‼️ 文件处理异常:{file_path}")
print(f"错误详情:{str(e)}")
print(f"\n{'='*50}")
print(f"扫描完成 | 处理文件:{file_count} 个 | 发现路径:{len(assets)} 条")
return assets
def extract_keys(file_paths):
"""提取并保存去重键值"""
keys = []
print(f"\n{'='*50}")
print("开始解析关键键值")
for path in file_paths:
if path.endswith('.xlsx'):
print(f"\n▸ 解析Excel文件:{os.path.basename(path)}")
try:
df = pd.read_excel(path)
excel_keys = df.iloc[:, 0].astype(str).dropna().tolist()
keys.extend(excel_keys)
print(f" ├─ 提取到 {len(excel_keys)} 条键值")
for key in excel_keys[:3]:
print(f" │ 示例:{key[:60]}...")
except Exception as e:
print(f"\n‼️ Excel文件读取失败:{path}")
print(f"错误详情:{str(e)}")
elif path.endswith('.asset'):
print(f"\n▸ 解析配置文件:{os.path.basename(path)}")
try:
with open(path, 'r', encoding='utf-8') as f:
line_count = 0
for line in f:
line_count += 1
clean_line = line.strip().replace("- ", "")
if "Assets/" in clean_line:
keys.append(clean_line)
print(f" ├─ [L{line_count:03d}] 发现键值:{clean_line[:40]}...")
except Exception as e:
print(f"\n‼️ 文件读取失败:{path}")
print(f"错误详情:{str(e)}")
keys = list(set(keys))
with open('keys.txt', 'w', encoding='utf-8') as f:
f.write('\n'.join(keys))
print(f"\n{'='*50}")
print(f"解析完成 | 去重键值:{len(keys)} 条")
print(f" ▹ 键值文件已保存:{os.path.abspath('keys.txt')}")
return keys
def validate_assets(assets, keys):
"""执行路径校验"""
errors = []
print(f"\n{'='*50}")
print("开始校验路径完整性")
print("\n校验进度:")
for idx, asset in enumerate(assets, 1):
if not any(key in asset['path'] for key in keys):
errors.append({
'file': asset['file'],
'sheet': asset['sheet'],
'path': asset['path']
})
print(f" ▹ 已校验 {idx}/{len(assets)} 条路径", end='\r')
print(f"\n\n{'='*50}")
if errors:
print(f"❌ 发现 {len(errors)} 条异常路径:")
for i, err in enumerate(errors[:5], 1):
print(f" {i:02d}. 文件:{err['file']} | 工作表:{err['sheet']}\n 路径:{err['path']}")
if len(errors) > 5:
print(f" ...(仅显示前5条,共{len(errors)}条)")
else:
print("✅ 所有路径均包含有效键值")
return errors
def main():
print(f"\n{'='*50}")
print("开始清理历史文件")
clean_old_files()
asset_files = [
r'..\MainProject\Assets\Build\AssetBundle\AssetBundleConfig.asset',
r'..\MainProject\Assets\Build\AssetBundle\SegmentedUpdateConfig.asset',
'代码路径.xlsx'
]
assets = collect_assets()
keys = extract_keys(asset_files)
errors = validate_assets(assets, keys)
if errors:
report_data = []
for err in errors:
report_data.append({
'来源文件': err['file'],
'工作表': err['sheet'],
'资源路径': err['path'],
'校验结果': 'Invalid'
})
report_df = pd.DataFrame(report_data)
report_path = "异常资源报告.xlsx"
report_df.to_excel(report_path, index=False)
print(f"\n📊 异常报告已生成:{os.path.abspath(report_path)}")
if __name__ == "__main__":
main()