2016-11-28 4 views
-2

파이썬을 사용하여 mysql 데이터베이스에서 일부 데이터를 추출하려고했지만 특수 문자 (데이터가 FR, ES, DE 및 IT 언어의 문자열) . 단어 (악센트 없음 등과 같은) 특수 문자가없는 어떤 파일 (I 추출 된 데이터가있는 CSV를 만드는거야) 이 제대로 인코딩 할 때마다 내가 사용하던 코드는파이썬에서 UTF-8로 인코딩 된 특수 문자를 읽는 방법

import mysql.connector 
if __name__ == '__main__': 

    cnx = mysql.connector.connect(user='user', password='psswrd', 
           host='slave', 
           database='DB', 
           buffered=True) 
    us_id_list = ['496305'] 

    f = open('missing_cat_mappings.csv', 'w') 
    for (us_id) in us_id_list: 
     print us_id 
     mapping_cursor = cnx.cursor() 
     query = (format(user_id=us_id,)) 
     success = False 
     fails = 0 
     while not success: 
      try: 
       print "try" + str(fails) 
       mapping_cursor.execute(query) 
       success = True 
      except: 
       fails += 1 
       if fails > 10: 
        raise 

     for row in mapping_cursor: 
      f.write(str(row) + "\n") 

     mapping_cursor.close() 
    f.close() 

    cnx.close() 

나는 덧붙였다 :

#!/usr/bin/python 
# vim: set fileencoding=<UTF-8> : 

처음에는 아무런 차이가 없었다.

+0

이 필요합니다? – runDOSrun

답변

0

은 기본적으로 당신은 인코딩이 UTF-8 그래서 방법을 알고 파이썬한다임을 지정합니까 open 바이너리 모드에서 CSV 파일, 'wb'되지 텍스트 모드 어디에도 코드에서 'w'

관련 문제