首页 > 解决方案 > 如何返回特定目录?

问题描述

在这段代码中,我试图打印一个选定的路径。每当我打印代码时,它都会显示正确的结果,但是当我返回此代码时,它会给我以下错误。

错误

Traceback (most recent call last):
  File "main.py", line 103, in <module>
    directory = listdirs(rootdir, 2)
  File "main.py", line 99, in listdirs
    return b[dir]
TypeError: list indices must be integers or slices, not str

代码

import os

subDir = []
def listdirs(path, dir):
    for roots, dirs, files in os.walk(path):
        for dir in dirs:
            d = os.path.join(roots, dir)
            subDir.append(d)
    b = [s.split(',') for s in subDir]
    return b[dir]
    # print(b[2])

rootdir = '/home/runner/TestP1'
directory = listdirs(rootdir, 2)
print(f"Selected directory: {directory}")

标签: pythonpython-3.x

解决方案


这里的问题是您使用相同的变量进行迭代和作为参数。

def listdirs(path, which_dir):
    for roots, dirs, files in os.walk(path):
        for dir in dirs:
            d = os.path.join(roots, dir)
            subDir.append(d)
    b = [s.split(',') for s in subDir]
    return b[which_dir]

rootdir = '/home/runner/TestP1'
directory = listdirs(rootdir, 2)
print(f"Selected directory: {directory}")

        

推荐阅读