[英]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
来file.seek
地设置读/写位置。
看到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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.