我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
当前回答
使用Python 3和Python 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-string替换:f"{item}\n"。
其他回答
使用Python 3和Python 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-string替换:f"{item}\n"。
简单:
with open("text.txt", 'w') as file:
file.write('\n'.join(yourList))
设avg为列表,则:
In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')
您可以根据自己的需求使用%e或%s。
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)