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)
名字和分数是多少?