import os folder_names = [] sections = [] section_data = {} vla_list=[] my_dict = {'front_middle_obs':34, 'obs_em':67 , 'track_em':67, 'front_radar_obs':67, 'front_middle_track':67, 'localization':10, } for root, dirs, files in os.walk(os.getcwd()): for dir_name in dirs: folder_names.append(dir_name) folder_count=0 for root, dirs, files in os.walk(os.getcwd()): folder_count += len(dirs) for i in range(1,folder_count+1): for key,value in my_dict.items(): if key == folder_names[i-1]: vla_list.append(value) for i in range(1, folder_count+1): section_name = f"section{i}" section_data[section_name] = {"\n"+"param1": f"{folder_names[i-1]}"+"\n", "param2": f"{vla_list[i-1]}"+"\n"} sections.append(section_data[section_name]) with open("check_timestamp.ini", "w") as f: for key, value in section_data.items(): f.write("[{}]".format(key)) for k, v in value.items(): f.write("{} = {}".format(k, v)) f.write("") 有语法错误马
时间: 2024-02-25 21:52:03 浏览: 102
这段代码看起来没有明显的语法错误。但是需要注意一些细节:
1. 变量 `section_data` 和 `vla_list` 在第一个 `for` 循环中被定义,但是它们的值没有被清空,而是在第二个 `for` 循环中被修改。因此,如果第一个 `for` 循环被执行多次,这些变量的值将被重复添加。可以在第二个 `for` 循环之前清空这些变量。
2. 在第二个 `for` 循环中,使用 `range(1,folder_count+1)` 遍历文件夹。但是,`folder_names` 的下标是从 0 开始的,因此,应该使用 `range(folder_count)` 来遍历。
3. 在将数据写入文件之前,应该将 `sections` 列表中的所有字典合并为一个字典。可以使用 `dict()` 和 `zip()` 函数来实现。
下面是修改后的代码:
```
import os
folder_names = []
sections = []
section_data = {}
vla_list = []
my_dict = {'front_middle_obs': 34,
'obs_em': 67,
'track_em': 67,
'front_radar_obs': 67,
'front_middle_track': 67,
'localization': 10}
for root, dirs, files in os.walk(os.getcwd()):
for dir_name in dirs:
folder_names.append(dir_name)
folder_count = 0
for root, dirs, files in os.walk(os.getcwd()):
folder_count += len(dirs)
# 清空 section_data 和 vla_list
section_data = {}
vla_list = []
for i in range(folder_count):
for key, value in my_dict.items():
if key == folder_names[i]:
vla_list.append(value)
for i in range(folder_count):
section_name = f"section{i+1}"
section_data[section_name] = {"\n"+"param1": f"{folder_names[i]}"+"\n",
"param2": f"{vla_list[i]}"+"\n"}
sections.append(section_data[section_name])
# 合并所有字典为一个字典
config_data = dict(zip(section_data.keys(), section_data.values()))
with open("check_timestamp.ini", "w") as f:
for key, value in config_data.items():
f.write("[{}]\n".format(key))
for k, v in value.items():
f.write("{} = {}".format(k, v))
f.write("\n")
```
希望能够帮到你!
阅读全文