我如何写一个列表文件?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()

其他回答

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

for item in items:
    filewriter.write(f"{item}" + "\n")
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

在Python3中你可以使用这个循环

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

这个逻辑首先将list中的项转换为字符串(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 

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

如果您只是试图将列表序列化到磁盘,以便稍后由同一python应用程序使用,则应该pickle该列表。

import pickle

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

再读一遍:

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