I am trying to read in a csv file data and store the data using a class. My variables are not defined in the file directly, but as an input from the csv file. I want to read the Line Ground
as an input for the class Building_Storey
and split the line using the class method from_st
.However I receive this error too many values to unpack (expected 4)
and the error message missing 3 required positional arguments
if I split the line Ground
earlier in the code.it seems that he reads the whole line as one string, and gives the first argument to the whole line. I don't know what is the problem with this code.
Input csv file:
TABLE;BuildingStorey;
GbxmlID;Name;Level;Internal Height;
F0;GroundFloor;0;3.7
F1;FirstFloor;4;3.7
F2;SecondFloor;16;8
The code :
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)
Output should be:
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
You could skip the first two "header" lines and then read each line in using Python's csv
library to automatically split the text into a list of values per row. If the list contains 4
entries, pass the values directly to your class using *
to pass each list element as an argument to your class:
import csv
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
with open('file.csv', newline='') as f_file:
csv_file = csv.reader(f_file, delimiter=';')
header_1 = next(csv_file)
header_2 = next(csv_file)
for row in csv_file:
if len(row) == 4:
floor = Building_Storey(*row)
print("ID: {}, Name: {}, Level: {}, Height: {}".format(floor.GbxmlID, floor.Name, floor.Level, floor.Internal_Height))
This would display:
ID: F0, Name: GroundFloor, Level: 0, Height: 3.7
ID: F1, Name: FirstFloor, Level: 4, Height: 3.7
ID: F2, Name: SecondFloor, Level: 16, Height: 8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.