我正在使用以下代码:
import csv
f = csv.writer(open("pe_ratio.csv","w"))
def factorial(n):
results = 1
# results are one because that is the minimum number
while n >= 1:
results = results * n
# results * nth number of n
n = n - 1
# n - 1
# two variables are affected in this program results and n
return f.writerow([results])
print factorial(4)
file.close()
我收到了这个错误:
Traceback (most recent call last):
File "pe_ratio.py", line 23, in <module>
print factorial(4)
File "pe_ratio.py", line 21, in factorial
return f.writerows([results])
_csv.Error: sequence expected
我怀疑我需要阅读CSV documentation并深入了解这个问题。我想要完成的是让csv文件连续写入factorial(4)的结果。我试过取出factorial(4)的打印功能,程序停止了。我在这里先向您的帮助表示感谢。
答案 0 :(得分:1)
import csv
with open("pe_ratio.csv", "w") as out_file:
f = csv.writer(out_file)
def factorial(n):
results = 1
# results are one because that is the minimum number
while n >= 1:
results = results * n
# results * nth number of n
n = n - 1
# n - 1
# two variables are affected in this program results and n
return f.writerow([results]) # <---note writerows vs writerow
print factorial(4)