+ 2
What's wrong with this code?
Can someone tell why is this code giving error? data = open('data.txt', 'w') data.write(" \n") data.write("56, 45, 65 \n56, 45, 67 \n12, 34, 63") data.close() f = open('data.txt', 'r') i = 0 while True: i = i + 1 line = f.readline() if not line: break m1 = line.split(",")[0] m2 = line.split(",")[1] m3 = line.split(",")[2] print(f"marks of student {i} is: {m1} ") print(f"marks of student {i} is: {m2} ") print(f"marks of student {i} is: {m3} ") print(line)
4 Answers
+ 5
your code is raising an error because the line.split(",") operation assumes that each line has exactly three values separated by commas
+ 5
Sap ,
to get a clear picture of all possible issues, it would be very helpful if you could give an output sample how the marks should be formatted and also what data type they should have.
see my comments in the attached file:
https://sololearn.com/compiler-playground/cpfoLdrNhgnH/?ref=app
+ 3
The problem in line 2.
data.write(" \n")
You are printing one blank line into the first line of the input file. That throws off when you read it back in because it doesn't have commas.
If you comment out that line, it works.
0
Thanks all of you!