在 Python 中: 假设我有一个循环,在每个循环中我都会生成一个具有以下格式的列表: ['n1','n2','n3'] 在每个循环之后,我想将生成的条目附加到一个文件(其中包含前一个循环的所有输出)。我该怎么做?
还有,有没有办法制作一个列表,其条目是这个循环的输出? IE。 [[],[],[]] 其中每个内部 []=['n1','n2','n3] 等
请您参考如下方法:
将单个列表作为一行写入文件
当然你可以把它写成一个文件,在把它转换成字符串之后:
with open('some_file.dat', 'w') as f:
for x in xrange(10): # assume 10 cycles
line = []
# ... (here is your code, appending data to line) ...
f.write('%r\n' % line) # here you write representation to separate line
一次写入所有行
关于问题的第二部分:
Also, is there a way to make a list whose entries are the outputs of this cycle? i.e.
[[],[],[]]where each internal[]=['n1','n2','n3']etc
它也很基础。假设你想一次全部保存,只需要写:
lines = [] # container for a list of lines
for x in xrange(10): # assume 10 cycles
line = []
# ... (here is your code, appending data to line) ...
lines.append('%r\n' % line) # here you add line to the list of lines
# here "lines" is your list of cycle results
with open('some_file.dat', 'w') as f:
f.writelines(lines)
将列表写入文件的更好方法
根据您的需要,您可能应该使用一种更专业的格式,而不仅仅是文本文件。您可以使用例如,而不是编写列表表示(可以,但不理想)。 csv模块(类似于Excel的电子表格):http://docs.python.org/3.3/library/csv.html
