2013-10-27 40 views
1

我用下面的代码:CSV Python的顺序错误

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)的打印功能,程序停滞。我在这里先向您的帮助表示感谢。

+2

请参阅http://stackoverflow.com/questions/441130/using-with-statement-for-csv-files-in-python/441446#441446更好的练习打开文件。 – tacaswell

+0

和http://docs.python.org/2/library/csv.html#csv.reader – tacaswell

回答

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)