Skip to main content
 首页 » 编程设计

python之将 'file' 变量传递给函数时出现 TypeError

2025年05月04日14pander-it

当我第一次将其编码为一个函数时,它起作用了。但是当我检查目录中的文件时我想做更多的事情,所以我将代码分为两个函数:一个检查目录中以 *.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 

请您参考如下方法:

在 python 2 中,有一个内置的 file,这就是您在 unrar 函数中调用 extract_archive 的内容。您没有使用 chktree 中的循环变量,因为它只存在于 chktree 中。你可以这样写:

def unrar(f): 
    patoolib.extract_archive(f, outdir="/root/tree/def") 
 
def chktree():     
    for f in glob.glob('/root/tree/down/*'): 
        if fnmatch.fnmatch(f, '*.rar'): 
            unrar(f) 

我使用 f 作为文件的名称,以防止屏蔽内置函数。