2010-07-16 39 views

回答

6

你可以做類似

import codecs 
try: 
    f = codecs.open(filename, encoding='utf-8', errors='strict') 
    for line in f: 
     pass 
    print "Valid utf-8" 
except UnicodeDecodeError: 
    print "invalid utf-8" 
+0

是擔任一個魅力對我來說!謝謝 – Somar 2017-02-27 12:34:39

18
def try_utf8(data): 
    "Returns a Unicode object on success, or None on failure" 
    try: 
     return data.decode('utf-8') 
    except UnicodeDecodeError: 
     return None 

data = f.read() 
udata = try_utf8(data) 
if udata is None: 
    # Not UTF-8. Do something else 
else: 
    # Handle unicode data 
+0

很明顯,我沒有做足夠好的功課,當有更多的解決方案簡單,因爲這:( 謝謝! – Jox 2010-07-16 23:53:07