Bar*_*rim 20 python python-3.x
我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)
这会将类似于数组的内容直接写入文本文件,即
['element1', 'element2', 'element3']
username@machine:/path$
Run Code Online (Sandbox Code Playgroud)
我要做的是创建文件
element1
element2
element3
username@machine:/path$
Run Code Online (Sandbox Code Playgroud)
我尝试了不同的循环方式并附加了一个"\n",但似乎写入是在一次操作中转储数组.问题类似于如何将字符串列表写入文件,添加换行符?但语法看起来像是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
Run Code Online (Sandbox Code Playgroud)
... ... Python shell给出了"TypeError:必须是str,而不是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')
Run Code Online (Sandbox Code Playgroud)
看起来我有"*text"问题的一部分(我读过这个扩展了参数,但直到你写了[元素]变成[[元素]]我才得到一个str-not-列表类型错误;我一直在想我需要告诉定义它是一个传递给它的列表/数组,而只是声明"test"将是一个字符串.)一旦我将它改为文本并使用了myfile,它就起作用了.用连接写,附加的\n放在文件末尾的最后一行.
agf*_*agf 38
myfile.close- 摆脱你使用的地方with.with自动关闭myfile,并且你必须调用close像close()反正它,当你不使用做任何事情with.你应该只使用withPython 3.
with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile:
myfile.write('\n'.join(lines))
Run Code Online (Sandbox Code Playgroud)
不要print用来写文件 - 使用file.write.在这种情况下,您希望在中间写入一些带有换行符的行,这样您就可以将行连接起来'\n'.join(lines)并将直接创建的字符串写入该文件.
如果元素lines不是字符串,请尝试:
myfile.write('\n'.join(str(line) for line in lines))
Run Code Online (Sandbox Code Playgroud)
首先转换它们.
您的第二个版本因其他原因不起作用.如果你通过
['element1', 'element2', 'element3']
Run Code Online (Sandbox Code Playgroud)
至
def save_to_file(*text):
Run Code Online (Sandbox Code Playgroud)
它会成为
[['element1', 'element2', 'element3']]
Run Code Online (Sandbox Code Playgroud)
因为*将每个参数放入一个列表中,即使你传递的内容已经是一个列表.
如果你想支持传递多个列表,并且仍然一个接一个地写,请执行
def save_to_file(*text):
with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile:
for lines in text:
myfile.write('\n'.join(str(line) for line in lines))
myfile.write('\n')
Run Code Online (Sandbox Code Playgroud)
或者,对于一个列表,摆脱*并做我上面做的.
编辑: @Arafangion是对的,您可能只是使用b而不是t写入您的文件.这样,您不必担心不同平台处理换行符的不同方式.
| 归档时间: |
|
| 查看次数: |
63066 次 |
| 最近记录: |