2016-01-18 22 views
0

需要帮助着写入文件按字母顺序的Python写为.txt字母

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

什么是名称和分数? –

回答

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) 
+0

非常感谢 –

0

你需要的file.seek调用设置读取/写入相应的位置。

查看seek() function?的一些解释。

相关问题