enumerate all the files in the current directory

CFileFind文件查找示例
本文介绍了一个使用CFileFind类进行文件查找的示例代码。通过实例演示了如何利用CFileFind类查找指定目录下的所有文件,并输出每个文件的名称。
   CFileFind finder;
   BOOL bWorking = finder.FindFile("*.*");
   while (bWorking)
   {
      bWorking = finder.FindNextFile();
      cout << (LPCTSTR) finder.GetFileName() << endl;
   }
def search_astra_datalog( directory: str = os.getcwd(), filelist: list = [], depth: int = 0, max_depth: int = 10, ) -> list: """ Traverse the files and folders from the current working directory downwards to find and collect astra data log. Parameters ---------- directory : str, default current working directory Used to specify the absolute starting directory path. By default, it starts from the directory path where the script is run, and you can also customize the directory path. filelist : list, default [] The directory path used to store the astra data log from the collected. The default is an empty list, or you can use a defined list. depth : int, default 0 Used to specify the starting directory level. If you know the exact starting directory level, you can define it here to reduce operating time. max_depth : int, default 10 Used to specify the ending directory level. You can specify the deepest directory level so that you can end the traversal early. Returns ------- list The returns contains the absolute directory path of all astra data logs. Notes ----- ...... """ new_directory = directory if os.path.isfile(directory): if ( "csv" in directory and not "event" in directory and not "tar.gz" in directory and "#" in directory ): filelist.append(directory) elif os.path.isdir(directory): if depth < max_depth: try: for s in os.listdir(directory): new_directory = os.path.join(directory, s) search_astra_datalog(new_directory, filelist, depth + 1, max_depth) except PermissionError: print(f"Access denied to directoryectory: {directory}") return filelist其中在前一循环输出的new_directory会被第二次循环中的new_directory=directory这一步赋值覆盖么?
08-06
KCONFIG-CONF(1) October 2017 KCONFIG-CONF(1) NAME kconfig-conf - Standalone implementation of the Linux Kconfig parser SYNOPSIS kconfig-conf [options] <KConfig_file> DESCRIPTION The kconfig toolkit support the Kconfig language and implement the parser and the configuration support associated to the KConfig files respecting the Linux kernel KConfig convention. At configuration time: • kconfig-mconf is based on ncurses (menuconfig) • kconfig-conf is based on dialog (config) • kconfig-gconf is based on GTK+ (gconfig) • kconfig-qconf is based on QT (qconfig) Associated tools: • kconfig-diff displays symbols diff between .config files OPTIONS –silentoldconfig Only for kconfig-conf, reload a given .config and regenerate header and command files accordingly. --allnoconfig Set all boolean configuration to no. --allyesconfig Set all boolean configuration to yes. --randconfig Generates a random configuration. ENVIRONMENT Environment variables for ‘*config’ KCONFIG_CONFIG This environment variable can be used to specify a default kernel config file name to override the default name of ".config". KCONFIG_OVERWRITECONFIG If you set KCONFIG_OVERWRITECONFIG in the environment, Kconfig will not break symlinks when .config is a symlink to somewhere else. CONFIG_ If you set CONFIG_ in the environment, Kconfig will prefix all symbols with its value when saving the configuration, instead of using the default, "CONFIG_". Environment variables for ‘{allyes/allmod/allno/rand}config’ KCONFIG_ALLCONFIG The allyesconfig/allmodconfig/allnoconfig/randconfig variants can also use the environment variable KCONFIG_ALLCONFIG as a flag or a filename that contains config symbols that the user requires to be set to a specific value. If KCONFIG_ALLCONFIG is used without a filename where KCONFIG_ALLCONFIG == "" or KCONFIG_ALLCONFIG == "1", "make *config" checks for a file named "all{yes/mod/no/def/random}.config" (corresponding to the *config command that was used) for symbol values that are to be forced. If this file is not found, it checks for a file named "all.config" to contain forced values. This enables you to create "miniature" config (miniconfig) or custom config files containing just the config symbols that you are interested in. Then the kernel config system generates the full .config file, including symbols of your miniconfig file. This 'KCONFIG_ALLCONFIG' file is a config file which contains (usually a subset of all) preset config symbols. These variable settings are still subject to normal dependency checks. Examples: KCONFIG_ALLCONFIG=custom-notebook.config make allnoconfig or KCONFIG_ALLCONFIG=mini.config make allnoconfig or make KCONFIG_ALLCONFIG=mini.config allnoconfig These examples will disable most options (allnoconfig) but enable or disable the options that are explicitly listed in the specified mini-config files. Environment variables for ‘randconfig’ KCONFIG_SEED You can set this to the integer value used to seed the RNG, if you want to somehow debug the behaviour of the kconfig parser/frontends. If not set, the current time will be used. KCONFIG_PROBABILITY This variable can be used to skew the probabilities. See /usr/share/doc/kconfig-frontends/kconfig.txt.gz. Environment variables for 'silentoldconfig' KCONFIG_NOSILENTUPDATE If this variable has a non-blank value, it prevents silent kernel config updates (requires explicit updates). KCONFIG_AUTOCONFIG This environment variable can be set to specify the path name of the "auto.conf" file. Its default value is "include/config/auto.conf". KCONFIG_TRISTATE This environment variable can be set to specify the path name of the "tristate.conf" file. Its default value is "include/config/tristate.conf". KCONFIG_AUTOHEADER This environment variable can be set to specify the path name of the "autoconf.h" (header) file. Its default value is "include/generated/autoconf.h". HISTORY June 2017, Man page originally compiled by Philippe Thierry (phil at reseau-libre dot com) Philippe Thierry kconfig-conf Man Page KCONFIG-CONF(1) 这是手册
08-08
import cantools import asammdf from asammdf import MDF, Signal import numpy as np import os import traceback import sys import can import glob def get_project_root(): “”“获取项目根目录(此脚本所在目录的父目录)”“” script_dir = os.path.dirname(os.path.abspath(file)) project_root = os.path.dirname(script_dir) return project_root def initialize_directories(): “”“初始化项目所需的所有目录结构”“” root = get_project_root() # 定义各文件夹路径 dirs = { 'blf_input': os.path.join(root, 'blf_files'), 'mdf_output': os.path.join(root, 'mdf_files'), 'dbc_files': os.path.join(root, 'dbc_files'), 'scripts': os.path.join(root, 'convert_script') } # 创建不存在的目录 for dir_path in dirs.values(): if not os.path.exists(dir_path): os.makedirs(dir_path) print(f"创建目录: {dir_path}") return dirs def select_file_from_directory(directory, file_extension): “”“从指定目录选择一个指定扩展名的文件”“” file_pattern = os.path.join(directory, f’*.{file_extension}') files = glob.glob(file_pattern) if not files: print(f"在目录 {directory} 中未找到 .{file_extension} 文件") return None # 如果只有一个文件,直接返回 if len(files) == 1: selected = files[0] print(f"自动选择 {file_extension.upper()} 文件: {os.path.basename(selected)}") return selected # 多个文件时让用户选择 print(f"\n在 {directory} 中找到以下 .{file_extension} 文件:") for i, file in enumerate(files, 1): print(f"{i}. {os.path.basename(file)}") while True: try: choice = int(input(f"请选择要使用的 {file_extension.upper()} 文件 (1-{len(files)}): ")) if 1 <= choice <= len(files): return files[choice - 1] else: print(f"请输入 1 到 {len(files)} 之间的数字") except ValueError: print("请输入有效的数字") def get_all_dbc_files(dbc_dir): “”“自动获取dbc_files目录中所有的DBC文件”“” dbc_files = [] # 获取目录中所有DBC文件 dbc_pattern = os.path.join(dbc_dir, '*.dbc') all_dbc_files = glob.glob(dbc_pattern) if not all_dbc_files: print(f"在目录 {dbc_dir} 中未找到任何DBC文件,将不进行信号解析") return dbc_files # 按文件名排序,确保每次加载顺序一致 all_dbc_files.sort() print(f"\n在 {dbc_dir} 中找到 {len(all_dbc_files)} 个DBC文件,将全部用于解析:") for i, file in enumerate(all_dbc_files, 1): print(f"CAN通道 {i}: {os.path.basename(file)}") return all_dbc_files def blf_to_mdf(blf_file_path, mdf_output_dir, dbc_file_paths=None): “”" 将BLF格式文件转换为MDF 3.x格式文件(.mdf后缀),支持多路CAN的DBC解析, 特别处理字符串型信号(如"err"),优化后解析效率更高 “”" try: # 验证输入文件是否存在 if not os.path.exists(blf_file_path): raise FileNotFoundError(f"BLF文件不存在: {blf_file_path}\n请检查文件路径是否正确") if not blf_file_path.endswith('.blf'): raise ValueError(f"输入文件不是BLF格式: {blf_file_path}\n请确保输入文件的扩展名为.blf") # 生成输出MDF文件路径 blf_filename = os.path.basename(blf_file_path) mdf_filename = os.path.splitext(blf_filename)[0] + '.mdf' mdf_file_path = os.path.join(mdf_output_dir, mdf_filename) print(f"输出MDF文件路径: {mdf_file_path}") # 确保输出目录存在 if not os.path.exists(mdf_output_dir): os.makedirs(mdf_output_dir, exist_ok=True) print(f"创建输出目录: {mdf_output_dir}") # 加载多个DBC文件(每个对应一路CAN) dbc_databases = {} if dbc_file_paths and len(dbc_file_paths) > 0: for can_channel, dbc_path in enumerate(dbc_file_paths, 1): # 从1开始编号CAN通道 if not os.path.exists(dbc_path): raise FileNotFoundError(f"DBC文件不存在: {dbc_path}\n请检查DBC文件路径是否正确") if not dbc_path.endswith('.dbc'): raise ValueError(f"DBC文件格式不正确: {dbc_path}\n请确保DBC文件的扩展名为.dbc") try: print(f"加载CAN通道 {can_channel} 的DBC文件: {os.path.basename(dbc_path)}") dbc = cantools.database.load_file(dbc_path) dbc_databases[can_channel] = dbc # 存储通道与DBC的映射 except Exception as e: raise RuntimeError(f"加载DBC文件 {os.path.basename(dbc_path)} 失败: {str(e)}") from e # 使用python-can读取BLF文件,这里直接迭代reader,减少列表存储开销 print(f"解析BLF文件: {os.path.basename(blf_file_path)}") message_count = 0 error_count = 0 # 存储信号数据,用集合辅助时间戳去重 signals_data = {} # 用于记录字符串信号的映射关系(信号名 -> {字符串: 编码值}) string_mappings = {} # 遍历BLF文件中的消息,直接迭代reader,避免先存列表再遍历 try: with can.BLFReader(blf_file_path) as reader: for msg in reader: message_count += 1 if message_count % 1000 == 0: # 每处理1000条消息显示进度 print(f"已处理 {message_count} 条消息...") # 验证消息对象是否包含必要属性 required_attrs = ['timestamp', 'arbitration_id', 'data', 'channel'] for attr in required_attrs: if not hasattr(msg, attr): error_count += 1 print(f"警告: 消息对象缺少必要属性 {attr},跳过这条消息") continue # 获取CAN通道号(通常从1开始) can_channel = msg.channel timestamp = msg.timestamp # 转换时间戳为纳秒(MDF使用纳秒时间戳),提升精度 try: timestamp_ns = int(round(timestamp * 1e9)) except (TypeError, ValueError) as e: error_count += 1 print(f"警告: 时间戳转换失败 - {str(e)},跳过这条消息") continue # 如果有DBC文件,尝试解析信号(按CAN通道匹配对应的DBC) if dbc_databases and can_channel in dbc_databases: dbc = dbc_databases[can_channel] try: if msg.arbitration_id in dbc._frame_id_to_message: message = dbc.get_message_by_frame_id(msg.arbitration_id) # 解码消息 decoded = message.decode(msg.data) # 存储每个信号,信号名包含CAN通道信息 for signal_name, signal_value in decoded.items(): full_signal_name = f"CAN{can_channel}.{message.name}.{signal_name}" if full_signal_name not in signals_data: signals_data[full_signal_name] = { 'timestamps': [], 'timestamps_set': set(), # 用集合辅助去重 'values': [] } # 快速检查重复:集合的in操作是O(1) current_ts = timestamp_ns while current_ts in signals_data[full_signal_name]['timestamps_set']: current_ts += 1 # 存在重复则偏移1纳秒 # 同时更新列表(保留顺序)和集合(用于后续去重) signals_data[full_signal_name]['timestamps'].append(current_ts) signals_data[full_signal_name]['timestamps_set'].add(current_ts) signals_data[full_signal_name]['values'].append(signal_value) else: # 处理DBC中未定义的CAN ID,包含通道信息 signal_name = f"CAN{can_channel}.UNDEFINED_ID_{msg.arbitration_id:03X}_Data" if signal_name not in signals_data: signals_data[signal_name] = { 'timestamps': [], 'timestamps_set': set(), # 用集合辅助去重 'values': [] } data_value = int.from_bytes(msg.data, byteorder='big') # 快速检查重复 current_ts = timestamp_ns while current_ts in signals_data[signal_name]['timestamps_set']: current_ts += 1 # 同时更新列表和集合 signals_data[signal_name]['timestamps'].append(current_ts) signals_data[signal_name]['timestamps_set'].add(current_ts) signals_data[signal_name]['values'].append(data_value) except Exception as e: error_count += 1 print( f"警告: 解码CAN{can_channel}消息 (ID: 0x{msg.arbitration_id:X}) 时出错 - {str(e)},跳过这条消息") continue else: # 没有对应DBC文件时,存储原始CAN消息,包含通道信息 try: signal_name = f"CAN{can_channel}.ID_{msg.arbitration_id:03X}_Data" if signal_name not in signals_data: signals_data[signal_name] = { 'timestamps': [], 'timestamps_set': set(), # 用集合辅助去重 'values': [] } # 将数据转换为整数表示 data_value = int.from_bytes(msg.data, byteorder='big') # 快速检查重复 current_ts = timestamp_ns while current_ts in signals_data[signal_name]['timestamps_set']: current_ts += 1 # 同时更新列表和集合 signals_data[signal_name]['timestamps'].append(current_ts) signals_data[signal_name]['timestamps_set'].add(current_ts) signals_data[signal_name]['values'].append(data_value) except Exception as e: error_count += 1 print( f"警告: 处理CAN{can_channel}消息 (ID: 0x{msg.arbitration_id:X}) 时出错 - {str(e)},跳过这条消息") continue print(f"消息处理完成 - 共处理 {message_count} 条消息,其中 {error_count} 条出错") if not signals_data: raise RuntimeError("未提取到任何信号数据,无法创建MDF文件") except Exception as e: raise RuntimeError(f"处理BLF消息时发生错误: {str(e)}") from e # 创建MDF文件(使用3.30版本生成.mdf格式) try: print("创建MDF文件(3.30版本,.mdf格式)...") mdf = MDF(version='3.30') # 添加所有信号到MDF signal_count = 0 for signal_name, data in signals_data.items(): # 仅用 timestamps 列表(已按顺序且去重)生成MDF if len(data['timestamps']) == 0 or len(data['values']) == 0: print(f"警告: 信号 {signal_name} 没有有效数据,已跳过") continue # 转换时间戳 try: timestamps = np.array(data['timestamps'], dtype=np.uint64) except Exception as e: print(f"警告: 信号 {signal_name} 时间戳转换失败 - {str(e)},已跳过") continue # 处理信号值(区分数值型和字符串型) try: # 尝试直接转换为数值型 values = np.array(data['values'], dtype=np.float64) is_string_signal = False except (TypeError, ValueError): # 转换失败,判定为字符串型信号,进行编码映射 is_string_signal = True if signal_name not in string_mappings: # 初始化映射表,用整数编码字符串(如"err"→1,"normal"→0) string_mappings[signal_name] = {} current_code = 0 else: current_code = len(string_mappings[signal_name]) # 逐个处理字符串值,生成编码 encoded_values = [] for val in data['values']: # 确保值是字符串(非字符串转为字符串) str_val = str(val) if str_val not in string_mappings[signal_name]: string_mappings[signal_name][str_val] = current_code current_code += 1 encoded_values.append(string_mappings[signal_name][str_val]) values = np.array(encoded_values, dtype=np.int32) # 创建信号对象 # 如果是字符串信号,在comment中记录映射关系 if is_string_signal: mapping_desc = "字符串映射: " + ", ".join([ f"{k}→{v}" for k, v in string_mappings[signal_name].items() ]) comment = f"字符串型信号。{mapping_desc} 从CAN{signal_name.split('.')[0][3:]}通道转换" else: comment = f"数值型信号。从CAN{signal_name.split('.')[0][3:]}通道转换的信号: {signal_name}" signal = Signal( samples=values, timestamps=timestamps, name=signal_name, unit='' if not is_string_signal else '编码值(见comment)', comment=comment ) # 添加信号到MDF mdf.append(signal) signal_count += 1 # 打印字符串信号的映射关系,方便用户查看 if is_string_signal: print(f"信号 {signal_name} 为字符串型,映射关系: {string_mappings[signal_name]}") if signal_count == 0: raise RuntimeError("没有有效信号可添加到MDF文件") print(f"已添加 {signal_count} 个信号到MDF文件") except Exception as e: raise RuntimeError(f"创建MDF文件时发生错误: {str(e)}") from e # 保存MDF文件 try: print(f"保存MDF文件到: {mdf_file_path}") mdf.save(mdf_file_path, overwrite=True) print("转换完成! 生成的是.mdf格式文件") print(f"MDF文件信息: {os.path.getsize(mdf_file_path)} 字节") except Exception as e: raise RuntimeError(f"保存MDF文件失败: {str(e)}") from e except Exception as e: # 输出详细错误信息 print(f"\n===== 转换失败 =====") print(f"错误类型: {type(e).__name__}") print(f"错误信息: {str(e)}") print(f"错误位置:") traceback.print_exc() raise def main(): # 初始化目录结构 print(“===== BLF 转 MDF 工具(支持字符串型信号) =====”) dirs = initialize_directories() print(f"\n项目根目录: {get_project_root()}") print(f"BLF文件目录: {dirs['blf_input']}") print(f"MDF输出目录: {dirs['mdf_output']}") print(f"DBC文件目录: {dirs['dbc_files']}") # 选择要转换的BLF文件 print("\n----- 选择BLF文件 -----") blf_file = select_file_from_directory(dirs['blf_input'], 'blf') if not blf_file: print("没有找到可转换的BLF文件,程序退出") sys.exit(1) # 自动获取所有DBC文件 print("\n----- 加载DBC文件 -----") dbc_files = get_all_dbc_files(dirs['dbc_files']) try: # 调用转换函数 blf_to_mdf(blf_file, dirs['mdf_output'], dbc_files) except Exception as e: print(f"程序执行失败: {str(e)}") sys.exit(1) input("\n转换完成,按任意键退出...") if name == “main”: main() 请在这段原有的代码上把修改的部分加上去
09-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值