-2

I would like to convert the result of the following:

def main():
    list = open('friends.txt').readlines()
    list.sort()
    f = open('friends_sorted.txt', 'w+')
    f.write(str(list))
    f.close()

if __name__ == '__main__':
    main()

from

['David\n', 'Geri\n', 'Jessica\n', 'Joe\n', 'John\n', 'Rose\n']

to

David
Geri
Jessica
Joe
John
Rose

--

How would I do this?

  • 5
    `"".join(my_list)` – Julien Mar 20 '18 at 00:59
  • @Julien: Or in this case, just `f.writelines(my_list)`, and skip the temporary string entirely, just letting `f` write each string one by one (with the loop at the C layer in CPython; minimal interpreter overhead). – ShadowRanger Mar 20 '18 at 01:13

1 Answers1

0

This is assuming your source data is in a file and looks/formatted like a list, but really isn't. When you open up the file and start to process it, it will be a string. So with that in mind other tasks need to be accomplished, mostly stripping out what isn't needed. Personally I think you need to format your source file better so that less work needs to be done. But here goes...

This is how the data looks in a file called 'friends.txt'

['David\n', 'Geri\n', 'Jessica\n', 'Joe\n', 'John\n', 'Rose\n']

#!python3

def main():
    s1 = ''; s2 = '' # strings to hold data being processed

    new_friends = [] # this will hold your new and exciting friends, but
                     # without the baggage of square brackets, quotes,
                     # new lines, or commas that are part of the string

    # use with open(), no closing of file required;
    # 'fp' stands for 'file pointer', call it whatever you want to call it;
    # all of the data in any file that gets opened up in this way is
    # always a string, it doesn't matter how it's formatted in the file
    with open('friends.txt', 'r') as fp:
        for line in fp:
            # strip out square brackets, quotes, and strings that look like
            # new lines but aren't new lines; split the statement over
            # 2 lines using a trailing backslash, doing so allows for easier
            # reading of the statement without excessive scrolling
            s1 = line.replace('[', '').replace(']', '') \
            .replace("'", '').replace('\\n', '')

        # strip out trailing new line
        s1 = s1.rstrip()

        # split() returns a list, split string on a 'comma/space'
        new_friends = s1.split(', ')

    # sort list, print results, build string that will be written to file
    for item in sorted(new_friends):
        print(item)        # print results
        s2 += item + '\n'  # build string

    # write to new file;
    # 'wf' stands for 'write file', call it whatever you want to call it
    with open('new_freinds.txt', 'w') as wf:
        wf.write(s2)

# start the program
if __name__ == '__main__':
    main()
Michael Swartz
  • 858
  • 2
  • 15
  • 27