2013-02-27 1 views
0

문자열 데이터 (UTF-8), 이진 (true/false/1/0) & 출력 데이터에 행으로 출력 할 정수 데이터가 포함 된 튜플이 있습니다. 내 코드의 일부이다 : 나는 "OutFile.write()"문의 여러 가지 버전을 시도했습니다str, UTF-8 및 int를 텍스트 파일에 어떻게 출력합니까?

### Python 2.73 

import fileinput 
import re 
import time 
import codecs 

uIDfile = '\Python\Fav Test\ppl.ttxt' 

InFile = open(uIDfile) 
OutFile = codecs.open('C:\Python\Fav Test\S2.ttxt', encoding='utf-8', mode='w') 

for user in InFile: 
    user = user [:-1] 
# user = unicode(user, 'utf-8').encode('utf-8') 

    if 'NNNN' in user: 
     break 
    else: 
     if '@N' in user: 
      try: 
       Grp = people_getGroups(user_id = user) 
       g = 0 
       if GetAll: 
        for group in Grp.find('groups').findall('group'): 

         g += 1 
         fErr = '' 
         uID = user 
         gID = group.get('ID') 
         gName = group.get('name') 
         tup = '\"{0}\"\t\"{2}\"\t\"{1}\"\t''\t{3}\t{4}\t{5}\t{6}\n'.format(uNSID, gNSID, gName, bin1, bin2, int1, int2) 
         OutFile.write(tup.encode('utf-8')) 

. 오류는 아래에 각각 나열되어 있습니다.

OutFile.write(codecs.utf_8_decode(tup.encode('utf-8'))) 
    TypeError: coercing to Unicode: need string or buffer, tuple found 

OutFile.write('\t'.join(codecs.utf_8_decode(tup.encode('utf-8')))) 
    TypeError: sequence item 1: expected string or Unicode, int found 

OutFile.write('\t'.join(map(str, codecs.utf_8_decode(tup.encode('utf-8'))))) 
    tup = '\"{0}\"\t\"{2}\"\t\"{1}\"\t""\t\"{3}\"\t\"{4}\"\t\"{5}\"\t\"{6}\"\n'.format(uNSID, gNSID, gName, str(bin1), str(bin2), str(int1), str(int2)) 
    UnicodeEncodeError: "'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)" 

OutFile.write('\t'.join(map(str, codecs.utf_8_decode(tup.encode('utf-8'))))) 
    tup = '\"{0}\"\t\"{2}\"\t\"{1}\"\t""\t\"{3}\"\t\"{4}\"\t\"{5}\"\t\"{6}\"\n'.format(uNSID, gNSID, gName, bin1, bin2, int1, int2) 
    UnicodeEncodeError: "'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)" 

모든 도움을 진심으로 감사드립니다.

답변

1

행을 파일로 출력하려면 csv module을 사용하는 것이 좋습니다. 여기 사용 방법의 예입니다

#-*- coding: utf-8 -*- 
import csv 
# Use of tempfile instead of hard-coded path, to be cross-platform :) 
import tempfile 
_, tmppath = tempfile.mkstemp() 
out = open(tmppath, 'w') 
writer = csv.writer(out) 
input = "Te×t Ðåtå".decode('utf-8') 
tup = (input.encode('utf-8'), 42, False) 
tup 
# OUT: ('Te\xc3\x97t \xc3\x90\xc3\xa5t\xc3\xa5', 42, False) 
writer.writerow(tup) 
out.close() 
print(u"Look at me : {}".format(tmppath)) 

당신은 사용할 수는 Dialects and Formatting Parameters 정확하게 OUPUT 파일 포맷해야하는 방법을 정의합니다. 이 good slides에 설명 된대로

, UTF8 걸림, 좋은 관행을 방지하기 위해 다음과 같습니다

  • 디코드 초기
  • 유니 코드 어디에서나 좋은 곳 "테 × 작동
  • 인코딩 후반
+0

t Ðåtå "는 tup에 직접 들어가지만,'uTxt ="TeThttp.encode ('utf-8'), 42, False와 같은 변수에서 오는 경우 어떻게 동작 할까?)'? 사실, uTxt는 실제로 파일의 필드를'uTxt = group.get ('name')처럼 읽으므로 사실이 아닙니다. encode ('utf-8')' –

+0

파일에서 읽을 때 또는 어디서든, "디코드 초기"원칙을 적용해야합니다. 나는 그 지점에 대한 나의 대답을 편집 할 것이다. (코드 가독성과 쉬운 실행을 위해서 변수 만 사용한다.) –

+0

도움 주셔서 감사합니다! 나는 문제를 발견했다 : 나는 OutFile = codecs.open ('C : \ Python \ Fav Test \ S2.ttxt', encoding = 'utf-8', mode = 'w')'을 사용하여 여전히 나에게 오류. 내가'OutFile = open ('C : \ Python \ Fav Test \ S2.ttxt', 'w')로 변경하면 잘 돌아갑니다! –

관련 문제