python - 如何返回特定目录?
问题描述
在这段代码中,我试图打印一个选定的路径。每当我打印代码时,它都会显示正确的结果,但是当我返回此代码时,它会给我以下错误。
错误
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}")
解决方案
这里的问题是您使用相同的变量进行迭代和作为参数。
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}")
推荐阅读
- sql - 为 BigQuery 中的每一天定义虚拟列
- javascript - 节点 js 和图表 js 的 ejs 对象存在问题
- ios - 如何在 Firestore 中获取文档密钥
- ruby-on-rails - 使用 mysql 数据库设计可跟踪的迁移错误
- amazon-web-services - 有没有其他方法可以使用 docker 容器安装亚马逊 S3 存储桶
- php - 将 nextjs 应用程序转换为 wordpress 简码
- node.js - 如何使用 tsserver + JSDoc 扩展 express.Request?
- c# - .NET 中所有可能引发的 XmlSchemaExceptions 的列表在哪里?
- javascript - 将状态从孩子传递给父母
- oracle - REST 代理在配置了 Basics 的 OSB 中不会阻止访问