简体   繁体   中英

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

I have a root directory with two subdirectories, cat and 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.

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 :

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. The latter has been around since Python 3.4, released in 2014, and there is no reason not to use it these days.

To only print the file names, but not the full paths, under a given root folder , you would do this:

from pathlib import Path

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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