将带有标头的数据写入.txt

时间:2014-01-28 14:28:10

标签: python io

我的代码包含一个循环,我想保存在每一步中获得的内容。现在我使用print index, peak_number, our_blob_area, our_blob_CM, filename打印变量;我怎么能把它们保存在一个文件中,标题是变量名称?

2 个答案:

答案 0 :(得分:1)

或许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()时,将使用逗号分隔的这些值写入新行。

答案 1 :(得分:0)

在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)