python sorting a list of words in a text file( test.txt)

306 Views Asked by At

I have a list of 5000 words in UNICODE format. how can I sort them after appending new words into it ???

 a = []
    for word in text:
        if word not in dic:
            misspelled = word
            a.append(misspelled)             
            foo =misspelled
            f = open('test.txt', 'a')
            f.write(foo.encode('utf8'))
            x='\n'
            f.write(x.encode('utf8'))
            f.close()
2

There are 2 best solutions below

6
On

Just sort them calling .sort:

a.sort()

You should also open the file once and use with to open your files:

with  open('test.txt', 'w') as f:      
    for word in text:
        if word not in dic:
            misspelled = word
            a.append(misspelled)
            foo = misspelled
            ..........
    a.sort() # sort
    for word in a:
        f.write("{}\n".format(word))
0
On

You could initialize a with the current list of words, then just spend to it as you go, like you are, and then sort a before writing it to the file.

f = file("test.txt", "r")
a = f.readlines()
. . . # Looping to find misspelled words, spending to a
f = file("test.txt", "w")
f.write("\n".join(sorted(a)).encode("utf-8")
f.close()