初學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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM