Skip to main content
 首页 » 编程设计

Python CSV 分隔符 : Separate Cells

2024年11月01日10del

我正在努力了解如何将分隔符功能与 CSV 一起使用。下面的代码是我目前所拥有的,但我想要做的是将每个项目放在 CSV 文件的单独单元格中。我试过这个example ...

import csv 
import datetime 
# imports modules 
 
now = datetime.datetime.now() 
# define current time when file is executed 
 
how = str(raw_input("How are you doing?")) 
why = str(raw_input("Why do you feel that way?")) 
scale_of_ten = int(raw_input("On a scale of 1-10. With 10 being happy and 1 being sad. How happy are you?")) 
#creates variables for csv file 
 
x = [now.strftime("%Y-%m-%d %H:%M"),how,why,scale_of_ten] 
# creates list for variables to be written in 
 
f = csv.writer(open("happy.csv","wb")) 
# creates f which makes a happy.csv type wb 
w = csv.writer(f, delimiter = ',') 
w.writerow([x]) 

我在运行代码时遇到以下错误:

Traceback (most recent call last): 
 File "journal.py", line 18, in <module> 
    w = csv.writer(f, delimiter = ',') 
TypeError: argument 1 must have a "write" method 

我如何将我的输入放入单独的单元格而不是一个?

请您参考如下方法:

您正在尝试从 csv.writer 创建一个 csv.writer;您应该在制作 f 时包含定界符参数并使用它。