Python将列表写入文本文件 [英] Python write a list to a text file

查看:774
本文介绍了Python将列表写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python format方法将数字列表写入文本文件.列表长度固定后,我可以执行以下操作:

I am using python format method to write a list of numbers into a text file. When the list length is fixed I can do:

a = [16,1,16,1]
myfile.write('{0},{1},{2},{3}'.format(*a) + "\n")

我的问题是,当列表大小不固定时,如何使用format方法.有任何简单的方法可以做到这一点吗?而不是先创建字符串b,然后将a映射到b,而不是.我不确定是否可以使用myfile.write('{all elements in a}'.format(*a) + "\n")

My question is how to use the format method when the size of list is not fixed. Is there any easy easy way of doing this? Rather than first create a string b, and then map a to b. I am not sure if I can use something like myfile.write('{all elements in a}'.format(*a) + "\n")

b=''
for i in range(len(a)):
    if i<(len(a)-1):
        b=b+'{'+ str(i) + '},'
    else:
        b=b+'{'+ str(i) + '}'

myfile.write(b.format(*a) + "\n")

推荐答案

使用str.join:

>>> lis = [16,1,16,1]
>>> ','.join(str(x) for x in lis) + '\n'
'16,1,16,1\n'
>>> lis = range(10)
>>> ','.join(str(x) for x in lis) + '\n'
'0,1,2,3,4,5,6,7,8,9\n'

这篇关于Python将列表写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆