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
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
In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')
您可以根据需要使用 %e 或 %s .
7
此逻辑将首先将列表中的项目转换为 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
一般
以下是 writelines() 方法的语法
fileObject.writelines( sequence )
示例
#!/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()
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())
12
你为什么不试试
file.write(str(list))
31
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
17 回答
你打算怎么处理这个档案?此文件是否适用于人类或具有明确互操作性要求的其他程序,或者您只是尝试将列表序列化到磁盘以供以后由同一个python应用程序使用 . 如果是第二种情况,那么你应该是pickleing列表 .
读回来:
你可以使用循环:
在Python 2中,您也可以使用
如果您热衷于单个函数调用,至少删除方括号
[]
,以便一次一个地创建一个字符串(genexp而不是listcomp) - 没有理由占用所有内存需要实现整个字符串列表 .使用逗号sepparated值将列表序列化为文本文件
迭代和添加换行符的另一种方法:
我认为探索使用genexp的好处会很有趣,所以这是我的看法 .
问题中的示例使用方括号来创建临时列表,因此等效于:
哪个不必要地构造了将要写出的所有行的临时列表,这可能会消耗大量内存,具体取决于列表的大小以及
str(item)
的输出有多详细 .删除方括号(相当于删除上面的包装
list()
调用)将改为将临时generator传递给file.writelines()
:此生成器将按需创建
item
对象的换行符(即,当它们被写出时) . 这很好,原因有两个:内存开销很小,即使对于非常大的列表也是如此
如果
str(item)
很慢,则在处理每个项目时文件中都会有明显的进展这可以避免内存问题,例如:
(我通过使用
ulimit -v 102400
将Python的最大虚拟内存限制为~100MB来触发此错误) .将内存使用放在一边,这种方法实际上并不比原始方法快:
(Linux上的Python 2.6.2)
如果你在python3上,你也可以使用print函数,如下所示 .
还有另一种方式 . 使用simplejson(在python 2.6中包含为json)序列化为json:
如果你检查output.txt:
这很有用,因为语法是pythonic,它是人类可读的,并且可以被其他语言的其他程序读取 .
使用 Python 3 和 Python 2.6+ 语法:
这与平台无关 . 它还使用换行符终止最后一行,这是一个UNIX best practice .
让avg成为列表,然后:
您可以根据需要使用
%e
或%s
.此逻辑将首先将列表中的项目转换为
string(str)
. 有时列表中包含一个元组该逻辑将写入一个新行中的每个元组 . 我们以后可以在读取文件时加载每个元组时使用
eval
:一般
以下是 writelines() 方法的语法
示例
参考
http://www.tutorialspoint.com/python/file_writelines.htm
最好的方法是:
因为我很懒....
你为什么不试试
工作原理:首先,使用内置的打开功能打开文件,并指定文件的名称和我们想要打开文件的模式 . 模式可以是读模式('r'),写模式('w')或附加模式('a') . 我们还可以指定我们是以文本模式('t')还是二进制模式('b')进行读,写或追加 . 实际上还有更多模式可供使用,帮助(开放)将为您提供更多有关它们的详细信息 . 默认情况下,open()认为文件是't'ext文件,并在'r'ead模式下打开它 . 在我们的示例中,我们首先在写文本模式下打开文件,并使用文件对象的write方法写入文件,然后我们最终关闭文件 .
The above example is from the book "A Byte of Python" by Swaroop C H. swaroopch.com