我正在尝试读取csv文件中的数据,并使用类存储数据。我的变量不是直接在文件中定义的,而是作为csv文件的输入。我想读取行Ground
作为类Building_Storey
的输入,并使用类方法from_st
拆分该行。但是,如果我在代码前面拆分行Ground
,我会收到此错误too many values to unpack (expected 4)
和错误消息missing 3 required positional arguments
。他似乎将整行作为一个字符串读取,并将第一个参数赋给整行。我不知道这个代码有什么问题
输入csv文件:
TABLE;BuildingStorey;
GbxmlID;Name;Level;Internal Height;
F0;GroundFloor;0;3.7
F1;FirstFloor;4;3.7
F2;SecondFloor;16;8
代码:
with open('file.csv', 'r')as fp:
copy = fp.readlines()
print(copy)
l = 0
for line in copy:
l = l + 1
if l == 3:
if 'GroundFloor' in line:
Ground = line
print(Ground)
class Building_Storey:
def __init__(self, GbxmlID, Name, Level, Internal_Height):
self.GbxmlID = GbxmlID
self.Name = Name
self.Level = Level
self.Internal_Height = Internal_Height
@classmethod
def from_st(cls, Story_st):
GbxmlID, Name, Level, Internal_Height = Story_st.split(';')
return cls(GbxmlID, Name, Level, Internal_Height)
Groundfloor = Building_Storey.from_st(Ground)
print(Groundfloor.GbxmlID)
print(Groundfloor.Name)
print(Groundfloor.Level)
print(Groundfloor.Internal_Height)
输出应为:
F0;GroundFloor;0;3.7;;;;;;; # the line I want to read
GroundFloor.GbxmlID = F0
GroundFloor.Name = GroundFloor
GroundFloor.Level = 0
GroundFloor.Internal_Height = 3.7
您可以跳过前两个“header”行,然后使用Python的
csv
库读取每一行,以自动将文本拆分为每一行的值列表。如果列表包含4
项,请使用*
将值直接传递给类,以将每个列表元素作为参数传递给类:这将显示:
相关问题 更多 >
编程相关推荐