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

标签 python

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

关于python - 将 'file' 变量传递给函数时出现 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34716450/

相关文章:

python - 从 ipython 中的另一个文件调用 Python 函数

Python 使用 RegEx 在网页中搜索列表中的匹配项

python - 打包密码软件并分发

python - Pyglet:火球射击游戏,每当我按下指定的键时,火球就会不断加速,而不是保持恒定速度

python - 如何将自己分配给自己的另一个实例

Python:根据数组中的值拆分 NumPy 数组

python - numpy 中检查向量是否对齐或方向相反的最快方法(截断的 SVD 后处理)

Python;链表和遍历!

python - 使用 python 搜索 json 中的值

python - 我当前的二叉搜索树实现有什么问题?最后打印树只打印根