Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python按字母顺序写入.txt_Python_Sorting_Alphabetical - Fatal编程技术网

Python按字母顺序写入.txt

Python按字母顺序写入.txt,python,sorting,alphabetical,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 th

需要帮助不能按字母顺序写入文件

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
来相应地设置读/写位置


有关说明,请参阅。

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

名字和分数是多少?