Python,os.listdir()错误

时间:2014-02-13 09:19:39

标签: python listdir

我正在写这个程序

def get_special_paths(dir):
    detected_paths = []
    paths = os.listdir(dir)
    for path in paths:
        if path == r'__\w+__':
            detected_paths.append(path)
    for element in detected_paths:
        index = detected_path.index(element)
        detected_paths[index] = os.path.abspath(element)
    return detected_paths

它会引发类型错误,如下所示:

Traceback (most recent call last):
  File"copyspecial.py", line 65, in <module>
    get_special_paths(dir)
  File"copysepcial.py", line 23, in get_special_paths
    paths = os.listdir(pathname)
TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found

该错误的含义是什么?如何解决?在此先感谢:)

2 个答案:

答案 0 :(得分:4)

您似乎已将dir内置函数传递给get_special_paths

>>> dir
<built-in function dir>

>>> os.listdir(dir)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found

将路径作为字符串传递。

get_special_paths('/path/to/dir')

顺便说一句,不要使用dir作为变量名。它会影响上面的dir函数。

答案 1 :(得分:0)

可能是因为此处未定义global_path

for element in detected_paths:
    index = detected_path.index(element) # Here detected_path is undefined

将其设为global_paths并尝试:

for element in detected_paths:
    index = detected_paths.index(element)