我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:

f.writelines([f"{line}\n" for line in lines])

当前回答

我想你在寻找这样的答案。

f = open('output.txt','w')
list = [3, 15.2123, 118.3432, 98.2276, 118.0043]
f.write('a= {:>3d}, b= {:>8.4f}, c= {:>8.4f}, d= {:>8.4f}, e= 
{:>8.4f}\n'.format(*list))
f.close()

其他回答

简单:

with open("text.txt", 'w') as file:
    file.write('\n'.join(yourList))
with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")

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

问题中的例子使用方括号来创建一个临时列表,因此相当于:

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

这将不必要地构造一个包含所有将被写入的行的临时列表,这可能会消耗大量的内存,这取决于列表的大小以及str(item)的输出有多详细。

去掉方括号(相当于去掉上面的包装列表()调用)将会传递一个临时生成器给file.writelines():

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

该生成器将按需创建以换行符结束的项目对象表示(即当它们被写入时)。这很好,有几个原因:

内存开销很小,即使对于非常大的列表也是如此 如果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

(我通过限制Python的max触发了此错误。使用ulimit -v 102400虚拟内存到~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

(Python 2.6.2 on Linux)

你还可以通过以下步骤:

例子:

my_list=[1,2,3,4,5,"abc","def"]
with open('your_file.txt', 'w') as file:
    for item in my_list:
        file.write("%s\n" % item)

输出:

在your_file.txt中,项目的保存方式如下:

1

2

3

4

5

abc

def

您的脚本也按上述方式保存。

否则,你可以用泡菜

import pickle
my_list=[1,2,3,4,5,"abc","def"]
#to write
with open('your_file.txt', 'wb') as file:
    pickle.dump(my_list, file)
#to read
with open ('your_file.txt', 'rb') as file:
    Outlist = pickle.load(file)
print(Outlist)

输出: [1,2,3,4,5, 'abc', 'def']

它保存转储列表,就像一个列表,当我们加载它时,我们能够读取。

同样由simplejson可能输出与上面相同的结果

import simplejson as sj
my_list=[1,2,3,4,5,"abc","def"]
#To write
with open('your_file.txt', 'w') as file:
    sj.dump(my_list, file)

#To save
with open('your_file.txt', 'r') as file:
    mlist=sj.load(file)
print(mlist)

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

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