简体   繁体   English

如何使用 python glob.glob() 打印子目录中的文件名

[英]How to print the file names in subdirectories with python glob.glob()

I have a root directory with two subdirectories, cat and dog.我有一个包含两个子目录 cat 和 dog 的根目录。 In there, I have a few text files.在那里,我有一些文本文件。 I'm trying to iterate through all the subdirectories and print the file names.我正在尝试遍历所有子目录并打印文件名。 Below is the code:下面是代码:

import glob
path = '/Users/msmacbook/Desktop/test/'
for x in glob.glob(path+'**/*'):
    print(x.replace(path, ""))

And here is the output:这是输出:

cat/cat1
cat/cat2
cat/cat3
dog/dog1
dog/dog2
dog/dog3

Where cat and dog are the subdirectories and cat1..etc, dog1..etc are the files.其中 cat 和 dog 是子目录,cat1..etc、dog1..etc 是文件。

How do I only print/retrieve the file names?如何只打印/检索文件名? I want the desired output to be我想要想要的输出

cat1
cat2
cat3
dog1
dog2
dog3

You can just split the path based on the / character and print the second (last) element,您可以根据/字符拆分路径并打印第二个(最后一个)元素,

for x in glob.glob(path+'**/*'):
    x = x.replace(path, "").split('/')
    print(x[-1])

You can use os.path.basename :您可以使用os.path.basename

import os
import glob

path = '/Users/msmacbook/Desktop/test/'

for x in glob.glob(path + '**/*'):
    print(os.path.basename(x))

The documentation of the glob module recommends to use the high-level path objects from the pathlib library. glob模块文档建议使用pathlib库中的高级路径对象。 The latter has been around since Python 3.4, released in 2014, and there is no reason not to use it these days.后者自 2014 年发布的 Python 3.4 以来一直存在,现在没有理由不使用它。

To only print the file names, but not the full paths, under a given root folder , you would do this:要在给定的根folder下仅打印文件名而不是完整路径,您可以这样做:

from pathlib import Path

folder = Path('/Users/msmacbook/Desktop/test')
for file in folder.rglob('*'):
    print(file.name)

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

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