0

Need help cant write to file alphabetically

class_name = "class 1.txt"    #adds '.txt' to the end of the file so it can be used to create a file under the name a user specifies
with open(class_name , 'r+') as file:
    name = (name)
    file.write(str(name + " : " )) #writes the information to the file
    file.write(str(score))
    file.write('\n')
    lineList = file.readlines()
    for line in sorted(lineList):
        print(line.rstrip())
Michael Recachinas
  • 2,739
  • 2
  • 20
  • 29
Nasrullah Khan
  • 53
  • 1
  • 1
  • 3

2 Answers2

0

You need calls of file.seek to set the read/write position accordingly.

See seek() function? for some explanations.

Community
  • 1
  • 1
jofel
  • 3,297
  • 17
  • 31
0

You should overwrite the file with the new (alphabetized) data. This is MASSIVELY easier than trying to track file.seek calls (which are measured in bytes, not lines or even characters!) and not significantly less performant.

with open(class_name, "r") as f:
    lines = f.readlines()

lines.append("{name} : {score}\n".format(name=name, score=score))

with open(class_name, "w") as f:  # re-opening as "w" will blank the file
    for line in sorted(lines):
        f.write(line)
Adam Smith
  • 52,157
  • 12
  • 73
  • 112