파일의 나머지 부분을 검사 할 필요가 없거나 ASCII 데이터를 포함하는 UTF-8 합법이라고 가정하면 encoding='utf-8'
및 errors='replace'
의 파일 open
을 사용할 수 있습니다. 유니 코드 대체 문자 으로 잘못된 바이트 (UTF-8 인코딩)가 변경됩니다. 또는 데이터를 보존하기 위해 errors
핸들러로 'surrogateescape'
을 사용할 수 있습니다.이 핸들러는 개인용 유니 코드 코드를 사용하여 나중에 실행 취소 할 수있는 원래 값을 나타냅니다. 당신은 다음과 같은 사람들을 위해 확인하실 수 있습니다 이동합니다
with open(csvname, encoding='utf-8', errors='replace', newline='') as f:
for PersonName, age, address in csv.reader(f):
if '\ufffd' in PersonName:
continue
... PersonName was decoded without errors, so process the row ...
또는 surrogateescape
, 당신은 비 UTF-8 데이터 (즉, 만약 "가능") 다른 분야에서 쓰기에 복원됩니다 보장 할 수 있습니다 :
with open(incsvname, encoding='utf-8', errors='surrogateescape', newline='') as inf,\
open(outcsvname, 'w', encoding='utf-8', errors='surrogateescape', newline='') as outf:
csvout = csv.writer(outf)
for PersonName, age, address in csv.reader(f):
try:
# Check for surrogate escapes, and reject PersonNames containing them
# Most efficient way to do so is a test encode; surrogates will fail
# to encode with default error handler
PersonName.encode('utf-8')
except UnicodeEncodeError:
continue # Had non-UTF-8, skip this row
... PersonName was decoded without surrogate escapes, so process the row ...
# You can recover the original file bytes in your code for a field with:
# fieldname.encode('utf-8', errors='surrogateescape')
# Or if you're just passing data to a new file, write the same strings
# back to a file opened with the same encoding/errors handling; the surrogates
# will be restored to their original values:
csvout.writerow([PersonName, age, address])
왜 '디코드'를 사용할 수 없습니까? – AChampion
그래서 나머지 필드의 인코딩은 무엇입니까? ASCII? 다른 것? 일반적으로 전체 _file_에는 단일 인코딩이 있으며 해당 단일 인코딩을 위반하면 데이터가 손상되었음을 의미하므로 실제로 신뢰할 수는 없습니다. ASCII 문자 만 포함하는 필드는 합법적 인 UTF-8 (UTF-8은 ASCII 수퍼 세트)입니다. – ShadowRanger
나는 들판의 나머지 부분에 대해 걱정하지 않는다. CSV 파일이 있고 PersonName에 UTF-8 문자 만 포함되어 있는지 확인하고 싶습니다. – user3990393