I am new to python and i am trying to read each line of file with comma ',' separated values. like this line:
435,567,897,905,6,56,22,90.
My existing code
#!/usr/bin/python
class Line():
def __init__(self, val1, val2, val3, val4, val5, val6, val7, val8):
self.val1 = val1
self.val2 = val2
self.val3 = val3
self.val4 = val4
self.val5 = val5
self.val6 = val6
self.val7 = val7
self.val8 = val8
def display(self):
print("CPU:",self.val1)
file = open("/Users/user/Desktop/data.txt", 'r')
for line in file:
line = line.split(",")
li = str(line)[1:-1]
lin = Line(li)
lin.display()
file.close()
data.txt is like below.
435,567,897,905,6,56,22,90
435,567,897,905,6,56,22,90
435,567,897,905,6,56,22,90
435,567,897,905,6,56,22,90
435,567,897,905,6,56,22,90
435,567,897,905,6,56,22,90
435,567,897,905,6,56,22,90
435,567,897,905,6,56,22,90
435,567,897,905,6,56,22,90
Please help me how to print first value like CPU:value.
2 Answers 2
You need to pass each of the items in each line to the Line constructor. One way to do it would be to write:
li = Line(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]))
but that's a lot of writing. Python has a shortcut:
li = Line(*line)
which will do the same thing.
Not sure why you were using str(line)[1:-1]...
Anyway, this means your code could be re-written to look like the following which also use a with statement which will automatically close the file after the loop:
class Line():
def __init__(self, val1, val2, val3, val4, val5, val6, val7, val8):
self.val1 = val1
self.val2 = val2
self.val3 = val3
self.val4 = val4
self.val5 = val5
self.val6 = val6
self.val7 = val7
self.val8 = val8
def display(self):
print("CPU:", self.val1)
with open("/Users/user/Desktop/data.txt", 'r') as file
for line in file:
line = line.split(",")
lin = Line(*line)
lin.display()
Comments
To unpack the values in a list into all the arguments of a function (in this case Line.__init__), use the * operator, like so:
lin = Line(*li)