Python opening a file and putting list of names on separate lines

Posted by Jeremy Borton on Stack Overflow See other posts from Stack Overflow or by Jeremy Borton
Published on 2011-11-20T01:30:18Z Indexed on 2011/11/20 1:51 UTC
Read the original article Hit count: 253

Filed under:

I am trying to write a python program using Python 3

I have to open a text file and read a list of names, print the list, sort the list in alphabetical order and then finally re-print the list. There's a little more to it than that BUT the problem I am having is that I'm supposed to print the list of names with each name on a separate line

Instead of printing each name on a separate line, it prints the list all on one line. How can I fix this?

    def main():

        #create control loop
        keep_going = 'y'

        #Open name file
        name_file = open('names.txt', 'r')

        names = name_file.readlines()

        name_file.close()

        #Open outfile
         outfile = open('sorted_names.txt', 'w')

        index = 0
        while index < len(names):
             names[index] = names[index].rstrip('\n')
             index += 1

        #sort names
        print('original order:', names)
        names.sort()
        print('sorted order:', names)

        #write names to outfile
        for item in names:
            outfile.write(item + '\n')
        #close outfile   
        outfile.close()

        #search names
        while keep_going == 'y' or keep_going == 'Y':

            search = input('Enter a name to search: ')

            if search in names:
                print(search, 'was found in the list.')
                keep_going = input('Would you like to do another search Y for yes: ')
            else:
                print(search, 'was not found.')

                keep_going = input('Would you like to do another search Y for yes: ')



    main()

© Stack Overflow or respective owner

Related posts about python-3.x