#python #anaconda #jupyter-notebook #visual-code #html #css #javascript #http

제목[re]csvwriter 관련 질문2020-05-26 16:27
작성자

1.우선 제가 quotechar의 기능을 옳게 이해했는지 궁금합니다.


[1, "hello", "1,2,3", "hi\nthere"]를 CSV파일로 넣으려 할때



1,hello,1,2,3,hi

there



이렇게 되지 않고



1,hello,?1,2,3?,?hi\nthere?



이렇게 되게 하려면 quotechar= '?'로 설정하면 되는건가요? 



>>>> 네 맞습니다.



2. 컴퓨터는 quoting을 할 것들을 감싸는 것을 "밖에 인식하지 못하나요?


ww= csv.writer(csvfile, delimiter=',', quotechar=' " ')

ww.writerow([?Hello there?, ?My name, is Dan?])



이라고 하면 ?에서 syntax error: invalid syntax 라고 뜨더라고요.



?를 쓴자리에 꼭 "를 써야 컴퓨터가 '아 이 부분을 quoting 하려는구나' 하고 인식할 수 있나요?



>>>> 답

writerow를 하는 구문은 python 구문입니다. python 인터프린터가 ?가 단독으로 사용되는 구문은 해석 할 수 없기 때문에 에러나 나는 겁니다.

즉 ?Hello there? 구문을 문자열로 인식할 수 없습니다. 해석이 불가능하니까요.


질문자님께서 원하신대로 ?로 구분을 하시려면 

ww= csv.writer(csvfile, delimiter=',', quotechar='?')

quotechar에 ?를 넣어주시면 됩니다.



3. "로 감싸도 quoting이 안되는 것들은 어떻게 quoting하나요? 


ww= csv.writer(csvfile, delimiter=',', quotechar=' " ')

ww.writerow(["Hello there", "My name, is Dan"])


위의 예시에서 Hello there는 가운데에 delimiter인 , 가 없기 때문에 quoting이 안되는거 같아요.


이는 quoting= QUOTE_MINIMAL이랑 관련 된거 같은데, QUOTE_MAX 뭐 이런거가 있어서


"로 감싼 부분은 사이에 delimiter가 있든없든 csv파일을 열었을때 무조건 quotechar로 감싸도록 할 방법이 없나요?



>>>> 답

네 기본적으로 QUOTE_MINIMAL로 작동하여 질문자님께서 보신대로 작동합니다.

원하시는 대로 하시려면 QUOTE_ALL을 사용하시면 됩니다.


예제 코드 첨부합니다.


import csv
with open("test.csv"'w'as f:
    ww = csv.writer(f, delimiter=','quotechar='?'quoting=csv.QUOTE_ALL)
    ww.writerow(['Hello there''My name, is Dan'])
댓글
이전csvwriter 관련 질문2020-05-26
다음step 16 class 실습 질문2020-05-26