用Python编写一个列表到一个文件 [英] Writing a list to a file with Python

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

问题描述

这是将列表写入文件的最简单方法,因为 writelines()不会插入换行符?

  file.writelines([%s\\\
%item for item in list])

似乎有一个标准的方式...

解决方案


编辑 Thomas 添加信息



不要忘记首先打开文件



thefile = open('test.txt' 'w')


我会使用循环:


$
thefile.write(%s\\\
%item)
  / pre> 

或:

  $ b print>> thefile,item 

如果您热衷于单个函数调用,最小删除方括号 [] 使得要打印的字符串一次被创建(一个genexp而不是一个listcomp) - 没有理由占用实现整个字符串列表所需的所有内存。


Is this the cleanest way to write a list to a file, since writelines() doesn't insert newline characters?

file.writelines(["%s\n" % item  for item in list])

It seems like there would be a standard way...

解决方案

EDIT Adding info from Thomas' comment

Don't forget to open the file first

thefile = open('test.txt', 'w')

I'd use a loop:

for item in thelist:
  thefile.write("%s\n" % item)

or:

for item in thelist:
  print>>thefile, item

If you're keen on a single function call, at least remove the square brackets [] so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.

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

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