梦书之家(移动开发)

你有一个苹果,我有一个苹果,我们交换一下,一人还是一个苹果;你有一个思想,我有一个思想,我们交换一下,一人就有两个思想。 ——肖伯纳

导航

初学Python常见的错误

1. TypeError: coercing to Unicode: need string or buffer, type found

Traceback (most recent call last):
  File "unzip.py", line 20, in <module>
    tar = tarfile.open(file)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tarfile.py", line 1658, in open
    return func(name, "r", fileobj, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tarfile.py", line 1720, in gzopen
    fileobj = bltn_open(name, mode + "b")
TypeError: coercing to Unicode: need string or buffer, type found

代码为:

#扫描当前目前下所有的gz文件
currDir = os.getcwd()
files = os.listdir(currDir)
dstDir = "201301_09"
if not os.path.exists(dstDir):
    os.mkdir(dstDir)
for fileName in files:
    if os.path.isfile(fileName) and tarfile.is_tarfile(fileName):
        print fileName
        try:
            tar = tarfile.open(file)#这里应该是fileName而不是file
            names = tar.getnames()
            for name in names:
                tar.extract(name,path=dstDir)
            tar.close()
        except tarfile.ReadError:
            print "not a tarFile"
            pass

 

posted on 2013-01-24 14:16  梦书  阅读(22647)  评论(0编辑  收藏  举报