文章目录
- python 读取C文件中数组中的数据
python 读取C文件中数组中的数据
例如可以使用 python 将 test.c 文件中数组:
unsigned short image[] = { 0x125, 0x123, 0x88, 0x99 }
中的所有数据生成到一个列表 list_num 中,并将其打印出来。
代码如下:
import re# 读取C源文件并提取数组数据
with open('test.c', 'r') as file: c_content = file.read()# 使用正则表达式查找十六进制数组(考虑空格和换行)
match = re.search(r'unsigned\s+short\s+image\[\]\s*=\s*\{([^}]+)\}', c_content)if not match: raise ValueError("Array not found in C file.")# 提取数组,去除空格,并按逗号分割
array_str = match.group(1).replace(',', ',') # 将中文逗号替换为英文逗号
hex_numbers = array_str.split(',')# 把十六进制字符串转换成整数并存储到列表
list_num = [int(hex_num.strip(), 16) for hex_num in hex_numbers if hex_num.strip()]# 打印列表
print(list_num)
当你运行这个脚本时,它会读取名为test.c
的文件,查找unsigned short image[]
数组定义,然后提取其中的十六进制数,转换成整数,并打印出来。
请确保test.c
文件在你的Python脚本可以访问的地方,或者提供完整的路径来定位该文件。此外,如果文件中含有中文逗号,脚本会将其替换为英文逗号以确保正确分割数值。