This is the 7th day of my participation in the August More Text Challenge

This article documents how Python gets all the files in a given folder.

The test environment

Create 3 folders and 11 files

glob

The glob module can return a file path that matches the specified matching pattern under the specified path (which can be absolute/relative).

  • *: Matches 0 or more arbitrary characters
  • ?: Matches a single character
  • []: Matches characters in the range (such as[a-d]Match a, b, c, d)

glob.glob

Returns the path list of all matched files. The parameter is pathname, which defines the path matching rule.

Case 1

import glob
file_path=The '*'
print(glob.glob(file_path))

>>> ['3'.'a'.'3b'.'b'.'1'.'2b'.'2a'.'1a'.'2'.'3a'.'glob_test.py'.'1b']
Copy the code

Use case 2

import glob
file_path=[0-9] '*'
print(glob.glob(file_path))

>>> ['3'.'d2'.'1'.'2'.'d3'.'d1']
Copy the code

Use case 3

import glob
file_path='? '
print(glob.glob(file_path))

>>> ['3'.'a'.'b'.'1'.'2']
Copy the code

Use case 4

import glob
file_path='*b'
print(glob.glob(file_path))

>>> ['3b'.'b'.'2b'.'1b']
Copy the code

glob.iglob

Iglob returns a generator object, one path per invocation.

import glob
file_path=The '*'
generator=glob.iglob(file_path)
for item in generator:
    print(item)

>>> 3
a
3b
d2
b
1
2b
2a
1a
2
d3
3a
glob_test.py
d1
1b
Copy the code

OS

Glob is convenient to use, but it can be seen from the above use-case output that glob is difficult to distinguish between folders and files, only the name, although the vast majority of cases of files have suffixes, in case in the past, in this supplement OS to return the specified folder under the file name method.

OS.walk

Os. walk(filepath) Returns all directories, files, and subdirectories and files under a specified directory.

import os
filePath = '. '
for i,j,k in os.walk(filePath):
    print(i,j,k)

>>> .'d2'.'d3'.'d1'] ['3'.'a'.'3b'.'b'.'1'.'2b'.'2a'.'1a'.'2'.'3a'.'glob_test.py'.'1b']
./d2 [] []
./d3 [] []
./d1 [] []
Copy the code
  • I: parent directory path
  • J: Folder in the parent directory
  • K: files in the parent directory

os.listdir

Os.listdir (filepath) and glob.glob(‘*’) have similar effects, returning all files in the folder and the folder name.

filePath = '. '    
print(os.listdir(filePath))

>>> ['3'.'a'.'3b'.'d2'.'b'.'1'.'2b'.'2a'.'1a'.'2'.'d3'.'3a'.'glob_test.py'.'d1'.'1b']
Copy the code

Access to the source code

The test environment and all the source code can be downloaded on Github.