【问题标题】:python write list to filepython将列表写入文件
【发布时间】:2015-05-29 15:42:28
【问题描述】:

来自this 的帖子,我一直在使用以下代码将列表/数组写入文件:

with open ("newhosts.txt",'w') as thefile:
    for item in hostnameIP:
      thefile.write("%s\n" % item)

hostnameIP 是:

[['localhost', '::1'], ['localhost', '::1'], ['localhost', '::1']]

在文件中,我得到了输出:

['localhost', '::1']
['localhost', '::1']
['localhost', '::1']

当我需要说的时候

localhost, ::1
localhost, ::1
localhost, ::1

最好的方法是什么?

【问题讨论】:

  • 两个回答都好,伙计们!
  • 你要接受哪个? :)

标签: python arrays list file


【解决方案1】:

用途:

with open ("newhosts.txt", "w") as thefile:
    for item in hostnameIP:
        thefile.write("%s\n" % ", ".join(item))

这样,项目的每个部分都将打印一个“,”作为分隔符。

但如果你想让代码更短,你也可以用换行符加入每个项目:

with open ("newhosts.txt", "w") as thefile:
    thefile.write("\n".join(map(", ".join, hostnameIP)))

【讨论】:

    【解决方案2】:
    with open ("newhosts.txt",'w') as thefile:
        for item in hostnameIP:
          thefile.write("%s, %s\n" % (item[0], item[1]))
    

    【讨论】:

      【解决方案3】:

      我会使用 csv 模块,只需在您的列表列表中调用 writerows:

      import csv
      lines = [['localhost', '::1'], ['localhost', '::1'], ['localhost', '::1']]
      with open ("newhosts.txt",'w') as f:
          wr = csv.writer(f)
          wr.writerows(lines)
      

      输出:

      localhost,::1
      localhost,::1
      localhost,::1
      

      【讨论】:

        【解决方案4】:

        据我所知,您有一个包含列表作为元素的列表。这就是为什么你得到你得到的结果。试试下面的代码(见第三行的小改动),你会得到想要的结果。

        with open ("newhosts.txt",'w') as thefile:
            for item in hostnameIP:
              thefile.write("%s\n" % ', '.join(item))
        

        【讨论】:

          【解决方案5】:

          您当前正在将列表的字符串表示形式打印到文件中。由于您只对列表的项目感兴趣,您可以使用str.format 和参数解包来提取它们:

          thefile.write("{}, {}\n".format(*item))
          

          【讨论】:

            猜你喜欢
            • 2012-12-11
            • 1970-01-01
            • 1970-01-01
            • 2010-10-28
            • 2017-05-21
            • 1970-01-01
            相关资源
            最近更新 更多