【发布时间】:2014-01-28 14:28:09
【问题描述】:
我的代码包含一个循环,我想保存在每个步骤中获得的内容。现在我正在使用print index, peak_number, our_blob_area, our_blob_CM, filename 打印变量;我怎样才能将它们保存在一个文件中,并在标题中说明变量名称?
【问题讨论】:
我的代码包含一个循环,我想保存在每个步骤中获得的内容。现在我正在使用print index, peak_number, our_blob_area, our_blob_CM, filename 打印变量;我怎样才能将它们保存在一个文件中,并在标题中说明变量名称?
【问题讨论】:
也许是csv module:
with open('outputfile.csv', 'wb') as outfh:
writer = csv.writer(outfh)
writer.writerow(['index', 'peak_number', 'our_blob_area', 'our_blob_CM', 'filename'])
for something in something_else:
writer.writerow([index, peak_number, our_blob_area, our_blob_CM, filename])
这将写入一行带有标题,然后每次您将另一个列表传递给writer.writerow() 时,都会用这些值写入一个新行,以逗号分隔。
【讨论】:
在 Python 2.x 中,print statement 可选择接受 >> file_object:
with open('filename', 'w') as f:
print >>f, 'index, peak_number, our_blob_area, our_blob_CM, filename'
for row in data_source:
print >>f, index, peak_number, our_blob_area, our_blob_CM, filename
在 Python 3.x 中,使用 print 作为函数并传递可选的 file 参数:
with open('filename', 'w') as f:
print('index, peak_number, our_blob_area, our_blob_CM, filename', file=f)
for row in data_source:
print(index, peak_number, our_blob_area, our_blob_CM, filename, file=f)
【讨论】: