Python 按字母顺序写入 .txt

Python writing to .txt 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())

您需要调用 file.seek 来相应地设置 read/write 位置。

请参阅 seek() function? 了解一些解释。

您应该用新的(按字母顺序排列的)数据覆盖该文件。这比尝试跟踪 file.seek 调用(以字节为单位,而不是行甚至字符!)要容易得多,而且性能也没有明显降低。

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)