使用Python将列表写入文件

问题描述 投票:515回答:17

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

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

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

python file list file-io newline
17个回答
739
投票

你可以使用一个循环:

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

在Python 2中,您也可以使用

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

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


12
投票
file.write('\n'.join(list))

8
投票
with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")

7
投票

如果你在python3上,你也可以使用print函数,如下所示。

f = open("myfile.txt","wb")
print(mylist, file=f)

3
投票

你为什么不试试

file.write(str(list))

2
投票

此逻辑将首先将列表中的项目转换为string(str)。有时列表中包含一个元组

alist = [(i12,tiger), 
(113,lion)]

该逻辑将在新行中写入每个元组的文件。我们以后可以在读取文件时加载每个元组时使用eval

outfile = open('outfile.txt', 'w') # open a file in write mode
for item in list_to_persistence:    # iterate over the list items
   outfile.write(str(item) + '\n') # write to the file
outfile.close()   # close the file 

1
投票

迭代和添加换行符的另一种方法:

for item in items:
    filewriter.write(f"{item}" + "\n")

-2
投票

让avg成为列表,然后:

In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')

您可以根据您的要求使用%e%s


-2
投票
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

工作原理:首先,使用内置的打开功能打开文件,并指定文件的名称和我们想要打开文件的模式。模式可以是读模式('r'),写模式('w')或附加模式('a')。我们还可以指定我们是以文本模式('t')还是二进制模式('b')进行读,写或追加。实际上还有更多模式可用,帮助(开放)将为您提供更多有关它们的详细信息。默认情况下,open()认为文件是't'ext文件,并在'r'ead模式下打开它。在我们的例子中,我们首先在写文本模式下打开文件,并使用文件对象的write方法写入文件,然后我们最终关闭文件。

上面的例子来自Swaroop C H.swaroopch.com的书“A Byte of Python”


318
投票

你打算怎么处理这个档案?此文件是否适用于人类或具有明确互操作性要求的其他程序?

如果您只是尝试将列表序列化到磁盘以供以后由同一个python应用程序使用,那么您应该将pickleing列表。

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)

读回来:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)

233
投票

最好的方法是:

outfile.write("\n".join(itemlist))

86
投票

还有另一种方式。使用simplejson序列化为json(在python 2.6中包含为json):

>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()

如果你检查output.txt:

[1, 2, 3, 4]

这很有用,因为语法是pythonic,它是人类可读的,并且可以被其他语言的其他程序读取。


85
投票

使用Python 3和Python 2.6+语法:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

这与平台无关。它还使用换行符终止最后一行,这是一个UNIX best practice


36
投票

我认为探索使用genexp的好处会很有趣,所以这是我的看法。

问题中的示例使用方括号来创建临时列表,因此等效于:

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

哪个不必要地构造了将要写出的所有行的临时列表,这可能会消耗大量内存,具体取决于列表的大小以及str(item)的输出的冗长程度。

删除方括号(相当于删除上面的包装list()调用)将通过临时generator传递给file.writelines()

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

此生成器将按需创建item对象的换行符(即,当它们被写出时)。这很好,原因有两个:

  • 即使对于非常大的列表,内存开销也很小
  • 如果str(item)很慢,则在处理每个项目时文件中都会有明显的进展

这可以避免内存问题,例如:

In [1]: import os

In [2]: f = file(os.devnull, "w")

In [3]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 385 ms per loop

In [4]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
...
MemoryError

(我通过使用ulimit -v 102400将Python的最大虚拟内存限制为~100MB来触发此错误)。

将内存使用放在一边,这种方法实际上并不比原来快:

In [4]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 370 ms per loop

In [5]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
1 loops, best of 3: 360 ms per loop

(适用于Linux的Python 2.6.2)


19
投票

使用逗号分隔值将列表序列化为文本文件

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )

18
投票

因为我很懒....

import json
a = [1,2,3]
with open('test.txt', 'w') as f:
    f.write(json.dumps(a))

#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
    a = json.loads(f.read())

14
投票

In General

以下是writelines()方法的语法

fileObject.writelines( sequence )

Example

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
seq = ["This is 6th line\n", "This is 7th line"]

# Write sequence of lines at the end of the file.
line = fo.writelines( seq )

# Close opend file
fo.close()

Reference

http://www.tutorialspoint.com/python/file_writelines.htm

© www.soinside.com 2019 - 2024. All rights reserved.