文字列データ(UTF-8)、バイナリ(true / false / 1/0)、および整数データを含むタプルがあり、出力ファイルに行として出力します。私のコードの一部は次のとおりです。
### 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()」ステートメントのいくつかの異なるバージョンを試しました。エラーはそれぞれ以下にリストされています。
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)"
どんな助けでも心から感謝します!