python – zipfile提取时的unicode错误

前端之家收集整理的这篇文章主要介绍了python – zipfile提取时的unicode错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个小脚本,它将提取.zip文件.
这很好用,但仅适用于.zip文件,它们的文件名中不包含带有“ä”,“ö”,“ü”(等等)字母的文件.
否则我收到此错误

  1. Exception in thread Thread-1:
  2. Traceback (most recent call last):
  3. File "threading.pyc",line 552,in __bootstrap_inner
  4. File "install.py",line 92,in run
  5. File "zipfile.pyc",line 962,in extractall
  6. File "zipfile.pyc",line 950,in extract
  7. File "zipfile.pyc",line 979,in _extract_member
  8. File "ntpath.pyc",line 108,in join
  9. UnicodeDecodeError: 'ascii' codec can't decode byte 0x94 in position 32: ordinal not in range(128)

这是我的脚本的提取部分:

  1. zip = zipfile.ZipFile(path1)
  2. zip.extractall(path2)

我怎么解决这个问题?

最佳答案
一个建议:

我这样做时收到错误

  1. >>> c = chr(129)
  2. >>> c + u'2'
  3. Traceback (most recent call last):
  4. File "

有一个unicode字符串传递到某处加入.

可能是zipfile的文件路径是用unicode编码的吗?
如果你这样做怎么办:

  1. zip = zipfile.ZipFile(str(path1))
  2. zip.extractall(str(path2))

或这个:

  1. zip = zipfile.ZipFile(unicode(path1))
  2. zip.extractall(unicode(path2))

这是ntpath中的第128行:

  1. def join(a,*p): # 63
  2. for b in p: # 68
  3. path += "\\" + b # 128

第二个建议:

  1. from ntpath import *
  2. def join(a,*p):
  3. """Join two or more pathname components,inserting "\\" as needed.
  4. If any component is an absolute path,all prevIoUs path components
  5. will be discarded."""
  6. path = a
  7. for b in p:
  8. b_wins = 0 # set to 1 iff b makes path irrelevant
  9. if path == "":
  10. b_wins = 1
  11. elif isabs(b):
  12. # This probably wipes out path so far. However,it's more
  13. # complicated if path begins with a drive letter:
  14. # 1. join('c:','/a') == 'c:/a'
  15. # 2. join('c:/','/a') == 'c:/a'
  16. # But
  17. # 3. join('c:/a','/b') == '/b'
  18. # 4. join('c:','d:/') = 'd:/'
  19. # 5. join('c:/','d:/') = 'd:/'
  20. if path[1:2] != ":" or b[1:2] == ":":
  21. # Path doesn't start with a drive letter,or cases 4 and 5.
  22. b_wins = 1
  23. # Else path has a drive letter,and b doesn't but is absolute.
  24. elif len(path) > 3 or (len(path) == 3 and
  25. path[-1] not in "/\\"):
  26. # case 3
  27. b_wins = 1
  28. if b_wins:
  29. path = b
  30. else:
  31. # Join,and ensure there's a separator.
  32. assert len(path) > 0
  33. if path[-1] in "/\\":
  34. if b and b[0] in "/\\":
  35. path += b[1:]
  36. else:
  37. path += b
  38. elif path[-1] == ":":
  39. path += b
  40. elif b:
  41. if b[0] in "/\\":
  42. path += b
  43. else:
  44. # !!! modify the next line so it works !!!
  45. path += "\\" + b
  46. else:
  47. # path is not empty and does not end with a backslash,# but b is empty; since,e.g.,split('a/') produces
  48. # ('a',''),it's best if join() adds a backslash in
  49. # this case.
  50. path += '\\'
  51. return path
  52. import ntpath
  53. ntpath.join = join

猜你在找的Python相关文章