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

Time:10-17

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

CodePudding user response:

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])

CodePudding user response:

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))

CodePudding user response:

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)
  • Related