将函数写入CSV文件

时间:2013-10-30 23:42:04

标签: python csv

我正在关注CSV documentation而我正在关注切线。如何将函数写入csv文件?我正在尝试使用以下代码将true_or_false(3)的结果写入一个单元格,但似乎我缺少括号,撇号或括号。当我尝试写它...我得到“无效的语法错误”

import csv
#import module

x = 5

def true_or_false(n):
    return n > x

print true_or_false(3)  

with open('eggs.csv', 'wb') as csvfile:
    #open csv file
    spamwriter = csv.writer(csvfile, delimiter= ' ',
                            quotechar= '|', quoting =csv.QUOTE_MINIMAL)
                            #quotechar is the character between apostrophes
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    # wrote down this
    spamwriter.writerow(['Spam' 'Lovely Spam', 'Wonderful Spam'])
    # wrote down that
    spamwriter.writerow(true_or_false(3)
    # how to write?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

嗯,首先,你需要关闭你的paren:

spamwriter.writerow(true_or_false(3))

第二,你需要把它放在list - writerow期望一个可迭代:

spamwriter.writerow([true_or_false(3)])

应该这样做。