[英]how to write list of tuples into new file using python
my_list=[('127.0.0.1', '-', '-', '06/Apr/2017:00:00:00 -0400',
'POST /Apps/js_recommanded_jobs.php HTTP/1.1',
'200', '20546', '-', '-'),
('127.0.0.1', '-', '-', '06/Apr/2017:00:00:00 -0400',
'POST /Apps/auto_suggestion_solr.php HTTP/1.1',
'200', '185', '-', '-')]
我需要如下输出:
('127.0.0.1', '-', '-', '06/Apr/2017:00:00:00 -0400', 'POST /Apps/js_recommanded_jobs.php HTTP/1.1', '200', '20546', '-', '-'),
('127.0.0.1', '-', '-', '06/Apr/2017:00:00:00 -0400', 'POST /Apps/auto_suggestion_solr.php HTTP/1.1', '200', '185', '-', '-')
如果需要将其另存为字符串,则可以执行以下操作。
将每个由定界符',\\ n'分隔的元组写入sample_file.txt
with open('sample_file.txt', 'wb') as new_file: new_list = map(str, my_list) new_file.write(",\\n".join(new_list))
希望能帮助到你!
演示:
>>> fp = open("myfile.txt", "w")
>>> for row in my_list:
... fp.write(str(row) + "\n")
...
>>> fp.close()
>>>
编辑2:最后使用map和string join方法删除不必要的逗号。
演示:
>>> fp = open("myfile.txt", "w")
>>> fp.write(",\n".join(map(str, my_list)))
>>> fp.close()
此代码有效。
with open('out.txt', 'w') as f:
for line in my_list:
f.write(str(line)+'\n')
这样就可以了。
with open('mylist.txt', 'w') as f:
my_list = [('a','b'),('b','c')]
listtocopy = ',\n'.join(str(x) for x in my_list)
f.write(listtocopy)
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.