首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,os.listdir()错误

Python,os.listdir()错误
EN

Stack Overflow用户
提问于 2014-02-13 09:19:39
回答 2查看 3.4K关注 0票数 0

我在写这个程序

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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

这个错误的含义是什么,我如何纠正它?(预先谢谢:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-13 09:21:22

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

代码语言:javascript
复制
>>> 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

以字符串的形式传递路径。

代码语言:javascript
复制
get_special_paths('/path/to/dir')

顺便说一句,不要使用dir作为变量名。它将遮挡上述dir函数。

票数 4
EN

Stack Overflow用户

发布于 2014-02-13 09:42:41

可能是因为这里没有定义global_path

代码语言:javascript
复制
for element in detected_paths:
    index = detected_path.index(element) # Here detected_path is undefined

让它成为global_paths,并尝试:

代码语言:javascript
复制
for element in detected_paths:
    index = detected_paths.index(element)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21749800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档