我有一个包含以下示例数据的csv文件:
[Network]
Network Settings
RECORDNAME,DATA
UTDFVERSION,8
Metric,0
yellowTime,3.5
allRedTime,1.0
Walk,7.0
DontWalk,11.0
HV,0.02
PHF,0.92
[Nodes]
Node Data
INTID,TYPE,X,Y,Z,DESCRIPTION,CBD,Inside Radius,Outside Radius,Roundabout Lanes,Circle Speed
1,1,111152,12379,0,,,,,,
2,1,134346,12311,0,,,,,,
3,3,133315,12317,0,,,,,,
4,1,133284,13574,0,,,,,,
我需要帮助来弄清楚如何使用python将其放置到两个单独的表中。到目前为止,我有以下代码,但当我尝试使用它时,我在“if row ['RECORDNAME '] == 'Network Settings':“上得到了一个键错误。
# Open the file
with open('filename.csv', 'r') as f:
# Create a reader
reader = csv.DictReader(f)
# Initialize empty lists for the tables
network_table = []
nodes_table = []
# Loop through the rows
for row in reader:
# Check if the row contains the "RECORDNAME" key
if 'RECORDNAME' in row:
# Check if the row belongs to the "Network" or "Nodes" section
if row['RECORDNAME'] == 'Network Settings':
# Add the row to the "Network" table
network_table.append(row)
elif row['INTID'] is not None:
# Add the row to the "Nodes" table
nodes_table.append(row)
# Print the tables
print(network_table)
print(nodes_table)
如有任何建议,我们将不胜感激。
1条答案
按热度按时间rsl1atfo1#
这是解决这个问题的一种方法,读取一个表的文件,然后存储那个数据。注解添加到代码中,希望它们有帮助。
可以像
result['Network Settings']
一样访问每个表。