Python: How do i sort data in a text file? -
i trying write inside .txt file , sort in alphabetical order names inside, print. how this? if can't done there alternative?
print("well done " + name + "! total score is: {}/10 :)\n".format(score)) #os.system("color 0a") time.sleep(3) file = open(str(age) + ".txt" , "a") # creates file.txt if hasn't been created , ammends 'a' file.write(name + " " + str(age) + " {}\n".format(score)) # writes file, .format(x) replaces {} variable x file.close f = open(str(age) + ".txt" , "r") lines = f.readlines() f.close() lines.sort() f = open(str(age) + ".txt" , "w") line in lines: f.write(line) print(lines) f.flush() f.close()
i guessing input looks -
a 10 1 b 10 2 c 10 8 d 10 5
making sure each name on separate line, not seem case code, since file.write() not automatically append \n
end, have manually -
file.write(name + " " + str(age) + " {}\n".format(score))
then can -
f = open(str(age) + ".txt" , "r") lines = f.readlines() f.close() lines.sort() f = open(str(age) + ".txt" , "w") line in lines: f.write(line) f.flush() f.close()
Comments
Post a Comment