使用 Python 将列表写入文件 [英] Writing a list to a file with Python

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

问题描述

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

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

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

似乎会有一种标准的方式......

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

推荐答案

你可以使用循环:

with open('your_file.txt', 'w') as f:
    for item in my_list:
        f.write("%s
" % item)

在 Python 2 中,您也可以使用

In Python 2, you can also use

with open('your_file.txt', 'w') as f:
    for item in my_list:
        print >> f, item

如果您热衷于单个函数调用,至少删除方括号 [],以便一次打印一个字符串(genexp 而不是 listcomp) -- 没有理由占用实现整个字符串列表所需的所有内存.

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天全站免登陆