Print list to txt file without [brackets]

This is the place for queries that don't fit in any of the other categories.

Print list to txt file without [brackets]

Postby kadoza » Mon Oct 07, 2013 7:07 pm

I am trying to take a list of names, alphabetize them and print them to a new list. Here is my code:

Code: Select all
names = []
newnames = []
with open("C:/names.txt", "r") as infile:
    for row in infile.readlines():
       name = row.split()
       names.append(name)
    for x in sorted(names):
        newnames.append(x)
    print newnames
f = open("C:/newnames.txt", "w")
f.write("\n".join(str(x) for x in newnames))
f.close()


my problem is that it prints fine except for the brackets:

['Bradley']
['Harold']
['Jackson']
['Lincoln']
['Mercury']
['Shane']
['Sharon']
['Sherry']
['Xavier']
['Zoolander']

I want that list without the brackets or quotations in a text file
kadoza
 
Posts: 3
Joined: Sat Sep 14, 2013 2:46 am

Re: Print list to txt file without [brackets]

Postby snippsat » Mon Oct 07, 2013 11:58 pm

Code: Select all
names = []
with open("names.txt") as infile:
    for row in infile.readlines():
        names.append(row.strip())

f = open("newnames.txt", "w")
f.write('\n'.join(sorted(names)))
f.close()

Or with a little more Python power.
Code: Select all
with open("names.txt") as infile,open('newnames1.txt', 'w') as outfile:
    outfile.write('\n'.join(sorted(i.strip() for i in infile)))
User avatar
snippsat
 
Posts: 218
Joined: Thu Feb 21, 2013 12:04 am


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests