【发布时间】:2016-01-11 07:47:31
【问题描述】:
当我第一次将其编码为单个函数时,它起作用了。但是当我检查目录中的文件时,我想做更多的事情,所以我将代码分为两个函数:一个检查以 *.rar 扩展名结尾的目录中的文件,如果它找到匹配的文件,它会将其解压缩到一个目录中。
import shutil, os, patoolib, fnmatch, glob
def unrar():
patoolib.extract_archive(file, outdir="/root/tree/def")
def chktree():
for file in glob.glob('/root/tree/down/*'):
if fnmatch.fnmatch(file, '*.rar'):
unrar()
chktree()
在函数chktree(): 的if 之后执行unrar() 不起作用。我想知道我做错了什么,这是输出:
Traceback (most recent call last):
File "autotube.py", line 16, in <module>
chktree()
File "autotube.py", line 14, in chktree
unrar()
File "autotube.py", line 6, in unrar
patoolib.extract_archive(file, outdir="/root/tree/def")
File "/usr/local/lib/python2.7/dist-packages/patoolib/__init__.py", line 676, in extract_archive
util.check_existing_filename(archive)
File "/usr/local/lib/python2.7/dist-packages/patoolib/util.py", line 389, in check_existing_filename
if not os.path.exists(filename):
File "/usr/lib/python2.7/genericpath.py", line 26, in exists
os.stat(path)
TypeError: coercing to Unicode: need string or buffer, type found
【问题讨论】:
-
你有什么理由不只是在做
glob.glob('/root/tree/down/*.rar')? -
不要将
file设置为变量名,它是Python中的内置名称 -
仔细观察后,看起来更像是“琐碎或语法错误”:使用了一个恰好在其他地方声明的未声明名称。也无法添加调试打印。
标签: python