繁体   English   中英

使用 Python 将列表写入文件,使用换行符

[英]Writing a list to a file with Python, with newlines

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

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

使用循环:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write(f"{line}\n")

对于 Python <3.6:

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

对于 Python 2,也可以使用:

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

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

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

如果您只是尝试将列表序列化到磁盘以供同一个 python 应用程序稍后使用,那么您应该对列表进行腌制

import pickle

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

读回来:

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

更简单的是:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(itemlist))

要确保项目列表中的所有项目都是字符串,请使用生成器表达式:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(str(item) for item in itemlist))

请记住, itemlist会占用内存,因此请注意内存消耗。

使用Python 3Python 2.6+语法:

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

这是独立于平台的。 它还以换行符结束最后一行,这是UNIX 最佳实践

从 Python 3.6 开始, "{}\n".format(item)可以替换为 f 字符串: f"{item}\n"

还有一种方式。 使用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]

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

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

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

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

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

删除方括号(相当于删除上面的包装list()调用)会将临时生成器传递给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)

因为我很懒......

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())

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

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

一般来说

以下是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()

参考

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

在 python>3 中,您可以使用print*进行参数解包:

with open("fout.txt", "w") as fout:
    print(*my_list, sep="\n", file=fout)

简单地:

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

如果您在 python3 上,也可以使用 print 功能,如下所示。

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

使用numpy.savetxt也是一种选择:

import numpy as np

np.savetxt('list.txt', list, delimiter="\n", fmt="%s")

你为什么不试试

file.write(str(list))

我最近发现 Path 很有用。 帮助我绕过with open('file') as f然后写入文件。 希望这对某人有用:)。

from pathlib import Path
import json
a = [[1,2,3],[4,5,6]]
# write
Path("file.json").write_text(json.dumps(a))
# read
json.loads(Path("file.json").read_text())

此逻辑将首先将列表中的项目转换为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 

您还可以通过以下方式:

例子:

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")

Python3 中你可以使用这个循环

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

将标准输出重定向到文件也可能对此有用:

from contextlib import redirect_stdout
with open('test.txt', 'w') as f:
  with redirect_stdout(f):
     for i in range(mylst.size):
        print(mylst[i])

我建议这个解决方案。

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

设 avg 为列表,然后:

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

您可以根据需要使用%e%s

我认为您正在寻找这样的答案。

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()
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

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

上面的例子来自 Swaroop C H. swaroopch.com的《A Byte of Python》一书

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM