簡體   English   中英

Python,os.listdir()錯誤

[英]Python, os.listdir() error

我正在寫這個程序

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

並引發aa類型錯誤,如下所示:

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

該錯誤的含義是什么,我該如何解決? 提前致謝 :)

好像您將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函數。

可能是因為未在此處定義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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM