问题
I am trying to take a list of names, alphabetize them and print them to a new list. Here is my code:
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 the text file
回答1:
It looks to me like you simply need to call the element of the list. The line name = row.split()
will split the row (which is a string) by whatever is in the parenthesis, in this case nothing. So
In [1]: "john".split()
Out[1]: ['john']
If you file is just a list of name eg: John Harry
Then you don't need to split the row, if you do however wish to then simply indexing the 0th element:
row.split()[0]
will give you what is in the list as opposed to the list.
回答2:
row.split
returns a list, so names contains lists. Use extend
instead:
names.extend(row.split())
来源:https://stackoverflow.com/questions/19233455/print-list-to-txt-file-without-brackets-in-python