The text file is "ics2o.txt" and I don't know how to print numbers next to the lines
import random
print ("----------------------------------------------------------")
print ("Student Name Student Mark")
print ("----------------------------------------------------------")
f = open("ics2o.txt")
for line in f:
x = len(f.readlines())
for i in range (x):
contents = f.read()
print(str(contents) str(random.randint(75,100)))
CodePudding user response:
for line in f:
x = len(f.readlines())
for i in range (x):
contents = f.read()
print(str(contents) str(random.randint(75,100)))
The problem is that you are reading the file in at least 3 different ways which causes none of them to work the way you want. In particular, f.readlines()
consumes the entire file buffer, so when you next do f.read()
there is nothing left to read. Don't mix and match these. Instead, you should use line
since you are iterating over the file already:
for line in f:
print(line str(random.randint(75,100)))
The lesson here is don't make things any more complicated than they need to be.
CodePudding user response:
- Firstly, doing
print("----...")
is a bad practice, at least use string multiplication:print("-"*10)
- Secondly, always open files using 'with' keyword. (u can google it up why)
- Thirdly, the code:
with open("ics2o.txt") as f: for i,j in enumerate(f): print(i,j)