2013-12-20 4 views
2

CSV로 구분 기호 기능을 사용하는 방법을 이해하고 있습니다. 아래 코드는 지금까지 가지고 있지만, CSV 파일에 대해 별도의 셀에 각 항목을 가져 오는 것입니다. 나는이 example이 ... 파이썬 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) '구분자 =' ''이미 기본값] 따라서 실제로 여기서 _anything_ 할 필요는 없습니다. – abarnert

답변

2

csv.writer에서 csv.writer를 만들려고합니다. f를 만들 때 구분자 인수를 포함시켜야합니다.

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

거의 다 왔어. 기본적으로 f는 단순히 파일 객체이거나 내 케이스의 fid이어야합니다. writer 메소드에 다른 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])