2014-03-25 62 views
1

我有一个程序在python中构建为python 2,但现在我必须重新构建它,并且已经将某些内容更改为python3,但不知何故,我的csv未加载并且说...Python unicode错误

的第一个例子未解决的参考的unicode(我已经看到了这里的解决方案,但它并没有在所有的工作) 并说尚未解决的引用文件,任何人可以帮助我PLZ提前THKS;)

def load(self, filename): 

    try: 
     f = open(filename, "rb") 
     reader = csv.reader(f) 
     for sub, pre, obj in reader: 
      sub = unicode(sub, "UTF-8").encode("UTF-8") 
      pre = unicode(pre, "UTF-8").encode("UTF-8") 
      obj = unicode(obj, "UTF-8").encode("UTF-8") 
      self.add(sub, pre, obj) 
     f.close() 
     print 
     "Loaded data from " + filename + " !" 

    except: 
     print 
     "Error opening file!" 

def save(self, filename): 
    fnm = filename ; 
    f = open(filename, "wb") 
    writer = csv.writer(f) 
    for sub, pre, obj in self.triples(None, None, None): 
     writer.writerow([sub.encode("UTF-8"), pre.encode("UTF-8"), obj.encode("UTF-8")]) 
    f.close() 

    print 
    "Written to " + filename 

回答

3
unicode(sub, "UTF-8") 

应该是

sub.decode("UTF-8") 

Python3统一strunicode类型,因此不再有一个内置的unicode转换运算符。


Python 3 Unicode HOWTO解释了很多差异。

Since Python 3.0, the language features a str type that contain Unicode characters, meaning any string created using "unicode rocks!" , 'unicode rocks!' , or the triple-quoted string syntax is stored as Unicode.

,并说明如何encodedecode涉及到另一个

Converting to Bytes

The opposite method of bytes.decode() is str.encode() , which returns a bytes representation of the Unicode string, encoded in the requested encoding.


而不是

file(...) 

使用open

I/O docs说明如何使用open以及如何使用with确保它关闭。

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

>>> with open('workfile', 'r') as f: 
...  read_data = f.read() 
>>> f.closed 
True 
+0

奏效;)​​感谢 和有关文件名u能解释一下吗? – user3460197

+0

请参阅我的编辑。 –

+0

没关系,非常感谢,这只是奇怪的一件事,它一切都像你说的那样工作,但它仍然不读我的csv:\但正如我说你的帮助是awsome队友我upvoted它 – user3460197