my questions is, how to i sort by the 1st letter of the person's name in a text file(A at the top going to Z at the bottom). I use python 3.4.3.
I have a text file containing names and scores: = ('test', ' ', 1) I've tried the code below however it doesn't seem to sort alphabetically.
age
= class number
file = open(str(age) + ".txt" , "a")
file.write(name + " " + " {}\n".format(score))
f = open(str(age) + ".txt" , "r")
lines = f.readlines()
f.close()
lines.sort()
f = open(str(age) + ".txt" , "w")
for line in lines:
f.write(line)
f.flush()
f.close()
print(lines)
The problem is probably in your file. The code you posted works fine for a .txt file such as:
Dave = 12
Peter = 5
Agnes = 4
Charles = 10
Mary = 8
Please post your file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.