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

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

当前回答

在Python 3中,你可以使用print和*进行参数解包:

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

其他回答

将stdout重定向到一个文件也可以用于此目的:

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

序列化列表到文本文件与逗号分隔值

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

更简单的是:

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

记住,项目列表占用内存,所以要注意内存消耗。

使用循环:

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)——没有理由占用物化整个字符串列表所需的所有内存。

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

How It Works: First, open a file by using the built-in open function and specifying the name of the file and the mode in which we want to open the file. The mode can be a read mode (’r’), write mode (’w’) or append mode (’a’). We can also specify whether we are reading, writing, or appending in text mode (’t’) or binary mode (’b’). There are actually many more modes available and help(open) will give you more details about them. By default, open() considers the file to be a ’t’ext file and opens it in ’r’ead mode. In our example, we first open the file in write text mode and use the write method of the file object to write to the file and then we finally close the file.

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