使用os.listdir仅显示目录

2024-04-26 14:45:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使python只通过os.listdir输出目录,同时指定通过raw_input列出哪个目录?

我所拥有的:

file_to_search = raw_input("which file to search?\n>")

dirlist=[]

for filename in os.listdir(file_to_search):
    if os.path.isdir(filename) == True:
        dirlist.append(filename)

print dirlist

现在,如果我(通过raw_input)输入当前工作目录,这实际上是可行的。但是,如果我输入其他内容,列表将返回空。我试图分割并克服这个问题,但每个代码片段都按预期工作。


Tags: topathin目录whichforinputsearch
1条回答
网友
1楼 · 发布于 2024-04-26 14:45:24

这是预期的,因为os.listdir只返回文件/目录的名称,所以找不到对象,除非您在当前目录中运行它。

您必须join到扫描的目录才能计算其工作的完整路径:

for filename in os.listdir(file_to_search):
    if os.path.isdir(os.path.join(file_to_search,filename)):
        dirlist.append(filename)

注意列表理解版本:

dirlist = [filename for filename in os.listdir(file_to_search) if os.path.isdir(os.path.join(file_to_search,filename))]

相关问题 更多 >