Search code examples
pythonsortingalphabetical

Python writing to .txt alphabetically


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())

Solution

  • 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)