Python CSV分隔符:单独的单元格

时间:2013-12-20 00:44:58

标签: python csv delimiter

我正在努力了解如何使用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

如何将输入转换为单独的单元格而不是单个单元格?

4 个答案:

答案 0 :(得分:2)

您正在尝试从csv.writer创建一个csv.writer;你应该在制作f时加入delimiter参数并使用它。

答案 1 :(得分:0)

csv.writer需要一个像object这样的文件。看起来你试图创建两次编写器。试试这个......

import csv
data = [1, 2, 3, 4]
with open('file.csv', 'w') as f:
    wtr = csv.writer(f)  # use the file as the argument to writer
    wtr.writerow(data)
    f.close()

答案 2 :(得分:0)

你快到了。基本上f应该只是我的case中的文件对象或fid。你给writer方法另一个csv.writer对象。 csv.writer第一个参数应该是一个文件ID,例如open('new.csv','w')

获取的文件ID
fid = open('new.csv','w')
w = csv.writer(fid,delimiter=',')

#write to file
fid.close()

答案 3 :(得分:0)

您不需要'w'变量,只需执行此操作:

f = csv.writer(open("happy.csv", "wb"), delimiter=',')
f.writerow([x])