简体   繁体   English

Python - 仅列出文件夹名称而不是完整目录

[英]Python - Only listing folder names and not full directory

I have a short python script that lists all the folders in a directory however it lists the full path name for each folder.我有一个简短的 python 脚本,它列出了目录中的所有文件夹,但是它列出了每个文件夹的完整路径名。 Is there a way to only list the folder name and not the path.有没有办法只列出文件夹名称而不是路径。

Here is the script:这是脚本:

import os

rootdir = xxx
for file in os.listdir(rootdir):
    d = os.path.join(rootdir, file)
    if os.path.isdir(d):
        print(d)

Here is the output:这是输出:

V:\DATABASES\0 Suspension\Suspensia Pictures\X01BJ0004
V:\DATABASES\0 Suspension\Suspensia Pictures\X01BJ0005
V:\DATABASES\0 Suspension\Suspensia Pictures\X01BJ0006
V:\DATABASES\0 Suspension\Suspensia Pictures\X01BJ0008
V:\DATABASES\0 Suspension\Suspensia Pictures\X01BJ0026
V:\DATABASES\0 Suspension\Suspensia Pictures\X01BJ0037
V:\DATABASES\0 Suspension\Suspensia Pictures\X01BJ0038
V:\DATABASES\0 Suspension\Suspensia Pictures\X01BJ0039
V:\DATABASES\0 Suspension\Suspensia Pictures\X01BJ0735

Any help would be great, thank you!任何帮助都会很棒,谢谢!

Let's take a look at this line:让我们看一下这一行:

os.path.join(rootdir, file)

Just looking at it, it "joins" rootdir with file ;只是看着它,它“加入” rootdirfile ; it appends file to rootdir , which is why full directories are being printed.它将file附加到rootdir ,这就是打印完整目录的原因。

If you want only the file name to be printed, the line d = os.path.join(rootdir, file) should be omitted.如果您只想打印文件名,则应省略d = os.path.join(rootdir, file)行。 Alternatively, just use file instead of d .或者,只需使用file而不是d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM