在Python中:假设我有一个循环,在每个循环中,我生成一个具有以下格式的列表:["n1","n2","n3"]在每个循环之后,我想写信将生成的条目附加到一个文件(其中包含前一个循环的所有输出)。我该怎么做?
另外,有没有办法制作一个列表,其条目是这个周期的输出?即[[],[],[]] 其中每个内部 []=['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('%rn' % line) # here you write representation to separate line
一次写入所有行
当谈到问题的第二部分时:
另外,有没有办法制作一个列表,其条目是这个周期的输出?即
[[],[],[]]
,其中每个内部[]
=['n1','n2','n3']
等
这也是非常基本的。假设你想一次保存它,只需写:
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('%rn' % 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)
将列表写入文件的更好方法
根据您的需要,您可能应该使用一种更专业的格式,而不仅仅是文本文件。与其编写列表表示(可以,但不理想),不如使用 eg。 csv
模块(类似于 Excel 的电子表格):http://docs.python.org/3.3/library/csv.html
f=open(file,'a') 第一个段落是文件的路径,第二个是模式,'a'是附加的,'w'是写入的,'r'是读取的,依此类推我的意见,你可以用f.write(list+'')在循环中写一行,否则你可以使用f.writelines(list),它也可以。
希望这可以帮助您:
lVals = []
with open(filename, 'a') as f:
for x,y,z in zip(range(10), range(5, 15), range(10, 20)):
lVals.append([x,y,z])
f.write(str(lVals[-1]))