gpt4 book ai didi

python - CSV Python 序列错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:26 26 4
gpt4 key购买 nike

我使用以下代码:

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 文件写入行阶乘(4)的结果。我尝试取出阶乘(4)的打印函数,但程序停止了。我在这里先向您的帮助表示感谢。

最佳答案

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)

关于python - CSV Python 序列错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19624466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com