search
HomeBackend DevelopmentPython TutorialPython method to traverse all files in a directory

os.walk generator
os.walk(PATH), PATH is a folder path, of course you can use it. Or.../this way.
What is returned is a list of triplet elements, each element represents the content of a folder. The first one is the content of the current folder.
The returned triple represents (the working folder, the list of folders under this folder, the list of files under this folder).
So,
Get all subfolders, that is (d represents this triplet):

os.path.join(d[0],d[1]);

Get all sub-files, that is:

 os.path.join(d[0],d[2]);

The following example uses two sets of loops. After traversing, a list of all file names is obtained and then all files are looped:

result = [os.path.join(dp, f) for dp, dn, fs in os.walk("_pages") for f in fs if os.path.splitext(f)[1] == '.html']
for fname in result:
 #do something

actually equals

result=[]
for dp, dn, fs in os.walk("_pages"):
 for f in fs:
 if (os.path.splitext(f)[1] == '.html'):
  result.append(os.path.join(dp, f))
for fname in result:
 #do something

Finally determine whether the html suffix is ​​used to obtain the file name. You can also use glob:

result = [y for x in os.walk(PATH) for y in glob.glob(os.path.join(x[0], '*.txt'))]

You can also use iterator methods:

from itertools import chain
import glob
result = (chain.from_iterable(glob.iglob(os.path.join(x[0], '*.txt')) for x in os.walk('.')))

Advanced
The standard file number traversal generator os.walk is both powerful and flexible. However, os.walk still lacks some detailed processing capabilities required by applications, such as selecting files according to a certain pattern and performing operations on all files (or directories). Sorting, or only traversing the current directory without entering its subdirectories, so the interface needs to be encapsulated.

import os, fnmatch 
 
def filter_files(dirname, patterns='*', single_level=False, yield_folders=False): 
  patterns = patterns.split(';') 
  allfiles = [] 
  for rootdir, subdirname, files in os.walk(dirname): 
    print subdirname 
    allfiles.extend(files) 
    if yield_folders: 
      allfiles.extend(dubdirname) 
    if single_level: 
      break 
  allfiles.sort() 
  for eachpattern in patterns: 
    for eachfile in fnmatch.filter(allfiles, eachpattern): 
        print os.path.normpath(eachfile) 

Description:
1.The difference between extend and append
Lists are implemented as classes. "Creating" a list actually instantiates a class. Therefore, lists can be manipulated in multiple ways. Lists can contain elements of any data type, and the elements in a single list do not need to be all of the same type. The append() method adds a new element to the end of the list. Accepting only one parameter, the extend() method only accepts a list as a parameter and adds each element of the parameter to the original list.
2. fnmatch module
The fnmatch module uses patterns to match file names. The pattern syntax is the same as that used in Unix shells. An asterisk (*) matches zero or more characters, and a question mark (?) matches a single character. You can also use square brackets to specify a character range, for example [0-9] represents a number, and all other characters match themselves.
1) fnmatch.fnmatch(name, pattern) method: tests whether name matches pattern and returns true/false
2) fnmatch.filter(names, pat) implements filtering or filtering of special characters in the list and returns a list of characters that match the matching pattern. Of course, names represents the list

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

How do you debug shebang-related issues?How do you debug shebang-related issues?Apr 30, 2025 am 12:17 AM

The methods to debug the shebang problem include: 1. Check the shebang line to make sure it is the first line of the script and there are no prefixed spaces; 2. Verify whether the interpreter path is correct; 3. Call the interpreter directly to run the script to isolate the shebang problem; 4. Use strace or trusts to track the system calls; 5. Check the impact of environment variables on shebang.

How do you remove elements from a Python array?How do you remove elements from a Python array?Apr 30, 2025 am 12:16 AM

Pythonlistscanbemanipulatedusingseveralmethodstoremoveelements:1)Theremove()methodremovesthefirstoccurrenceofaspecifiedvalue.2)Thepop()methodremovesandreturnsanelementatagivenindex.3)Thedelstatementcanremoveanitemorslicebyindex.4)Listcomprehensionscr

What data types can be stored in a Python list?What data types can be stored in a Python list?Apr 30, 2025 am 12:07 AM

Pythonlistscanstoreanydatatype,includingintegers,strings,floats,booleans,otherlists,anddictionaries.Thisversatilityallowsformixed-typelists,whichcanbemanagedeffectivelyusingtypechecks,typehints,andspecializedlibrarieslikenumpyforperformance.Documenti

What are some common operations that can be performed on Python lists?What are some common operations that can be performed on Python lists?Apr 30, 2025 am 12:01 AM

Pythonlistssupportnumerousoperations:1)Addingelementswithappend(),extend(),andinsert().2)Removingitemsusingremove(),pop(),andclear().3)Accessingandmodifyingwithindexingandslicing.4)Searchingandsortingwithindex(),sort(),andreverse().5)Advancedoperatio

How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor