Search code examples
pythonlistsortingnames

Sorting names in a text file, writing results to another text file


I have a csv file containing a few names that are written in one line seperated by commas but no spaces ex. "maho,baba,fika,anst,koka,root". What i would like to do is to sort these names alphabetically and write them to a new text file so the result becomes like this:
anst
baba
fika
etc.

This is my attempt at it which did not work..

names = list()
filename = 'users.csv'
with open (filename) as fin:  
      for line in fin:
            names.append(line.strip())

names.sort()
print(names)

filename = 'names_sorted1.txt'
with open (filename, 'w') as fout:
      for name in names:
            fout.write(name + '\n')

Solution

  • You can use this oneliner:

    with open("names.csv") as f, open("new.csv", "w") as fw:
        [fw.write(x+"\n") for x in sorted([x for x in ",".join(f.readlines()).split(",")])]
    

    new.csv

    anst
    baba
    fika
    koka
    maho
    root


    Demo