python - Sorting Lists into Alphabetical Order -
i have list want sort alphabetical order, not working. have written this, not work well:
#!usr/bin/python f = open("test.txt","r") #opens file name of "test.txt" mylist = [] line in f: mylist.append(line) f.close() print mylist sublist = [] in range(1, len(mylist)): print mylist[i] sublist.append(mylist[i]) sublist.sort() print sublist
this text file:
test list ball apple cat digger elephant
and output:
enigmatist:python lbligh$ python test.py ['test list\n', 'ball\n', 'apple\n', 'cat\n', 'digger\n', 'elephant'] ball apple cat digger elephant ['apple\n', 'ball\n', 'cat\n', 'digger\n', 'elephant']
any troubleshooting extremely helpful. thanks
n.b. using python 2.7.9
you've forgotten overwrite file, that's all.
with open('test.txt', 'r') inf: lst = inf.readlines() # easier iterating , accumulating lst[1:] = sorted(lst[1:]) # leave first line: "test list" intact open('test.txt', 'w') outf: outf.writelines(lst) # re-write file
Comments
Post a Comment