2013-12-20 182 views
2

我正在理解如何使用帶有CSV的分隔符功能。下面的代碼是我到目前爲止,但我正在嘗試做的是讓每個項目在一個單獨的單元格中的CSV文件。我想這example ...Python CSV分隔符:分隔單元

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 

我將如何得到我的投入單獨的細胞,而不是一個?

+0

作爲附帶說明:['定界符= '''已經是默認](http://docs.python.org/3/library/csv.html#csv.Dialect.delimiter) ,所以你實際上不需要在這裏做任何事情。 – abarnert

回答

2

您試圖從csv.writer創建一個csv.writer;你應該在製作f時加入分隔符參數,然後使用它。

0

csv.writer需要像對象一樣的文件。它看起來像你試圖創造兩次作家。試試這個......

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() 
0

你幾乎在那裏。基本上f應該只是一個文件對象或FID在我的case.You給作家的方​​法另一個csv.writer對象。該csv.writer第一個參數是一個文件ID,這樣的開放式(「new.csv」,「W」)

fid = open('new.csv','w') 
w = csv.writer(fid,delimiter=',') 

#write to file 
fid.close() 
0

後天你不需要的「W」變量,只是這樣做:

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