繁体   English   中英

如何使用python将元组列表写入新文件

[英]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', '-', '-')

如果需要将其另存为字符串,则可以执行以下操作。

  • 以写入模式打开一个名为sample_file.txt的文件
  • 将my_list的每个元素映射到String
  • 将每个由定界符',\\ 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)) 

希望能帮助到你!

  1. 在写入模式下打开文件。
  2. 迭代输入列表中的每一行。
  3. 将行写入文件并添加新行init。
  4. 关闭文件。

演示:

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM