我想写一个数组(列表?)到使用Python 3的文本文件。目前我有:def save_to_file(*text):
with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile:
for lines in text:
print(lines, file = myfile)
myfile.close
它将看起来像数组的内容直接写入文本文件,即['element1', 'element2', 'element3']
username@machine:/path$
我要做的是用element1
element2
element3
username@machine:/path$
我尝试了不同的方法来循环并附加一个“\n”,但似乎写操作正在一次操作中转储数组。这个问题类似于How to write list of strings to file, adding newlines?,但是语法看起来像是针对Python 2的?当我尝试修改版本时:def save_to_file(*text):
myfile = open('/path/to/filename.txt', mode='wt', encoding='utf-8')
for lines in text:
myfile.write(lines)
myfile.close
…Python shell给出了“TypeError:must be str,not list”,我认为这是因为Python2和Python 3之间的更改。我在换行时缺少什么?
编辑:感谢@agf和@arafangion,结合你们的写作,我想到:def save_to_file(text):
with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile:
myfile.write('\n'.join(text))
myfile.write('\n')
看起来我有一部分问题是关于“*text”(我读过扩展参数的文章,但直到你写下[element]变成了[element]]我才得到str而不是list类型的错误;我一直在想,我需要告诉定义,它得到了一个传递给它的列表/数组,只要声明“test”就是一个字符串。)当我将它改为纯文本并将myfile.write与join一起使用,并且在文件末尾的最后一个换行符中添加额外的内容时,它就工作了。