Print list to txt file without [brackets] in PYTHON

混江龙づ霸主 提交于 2021-02-17 05:37:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!