Python按字母顺序写入.txt

时间:2016-01-18 19:01:11

标签: python sorting alphabetical

需要帮助无法按字母顺序写入文件

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

2 个答案:

答案 0 :(得分:0)

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

有关解释,请参阅seek() function?

答案 1 :(得分:0)

您应该使用新的(按字母顺序排列的)数据覆盖该文件。这比试图跟踪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)