【发布时间】:2011-08-21 13:59:31
【问题描述】:
我正在尝试使用 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 -not-list 类型错误;我一直在想我需要告诉定义它正在获取传递给它的列表/数组,并且仅说明“test”将是一个字符串。)一旦我将其更改为文本和使用 myfile.write 和 join,附加的 \n 放在文件末尾的最后一个换行符中。
【问题讨论】:
标签: python python-3.x