2

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.

martineau
124k29 gold badges181 silver badges319 bronze badges
asked May 31, 2016 at 23:22

2 Answers 2

1

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()
answered May 31, 2016 at 23:42
Sign up to request clarification or add additional context in comments.

Comments

0

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)
answered May 31, 2016 at 23:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.