简体   繁体   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', '-', '-')]

I need output as like below: 我需要如下输出:

('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', '-', '-')

If you need to save it as the String, you may do the following. 如果需要将其另存为字符串,则可以执行以下操作。

  • Open a file in write mode, named as sample_file.txt 以写入模式打开一个名为sample_file.txt的文件
  • Map every element of my_list to String 将my_list的每个元素映射到String
  • Writing every tuple separated by delimiter ',\\n' to sample_file.txt 将每个由定界符',\\ 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)) 

Hope it helps! 希望能帮助到你!

  1. Open File in write mode. 在写入模式下打开文件。
  2. Iterate every row from input list. 迭代输入列表中的每一行。
  3. Write row into file and add new line init. 将行写入文件并添加新行init。
  4. Close file. 关闭文件。

Demo: 演示:

>>> fp = open("myfile.txt", "w")
>>> for row in my_list:
...     fp.write(str(row) + "\n")
... 
>>> fp.close()
>>> 

Edit 2: Remove unnecessary comma at the end by using map and string join method. 编辑2:最后使用map和string join方法删除不必要的逗号。

Demo: 演示:

>>> fp = open("myfile.txt", "w")
>>> fp.write(",\n".join(map(str, my_list)))
>>> fp.close()

This code works. 此代码有效。

with open('out.txt', 'w') as f:
    for line in my_list:
        f.write(str(line)+'\n')

This will do the job. 这样就可以了。

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