search
HomeBackend DevelopmentPython TutorialSimply master the usage of glob module to find file paths in Python

glob使用UNIX shell规则查找与一个模式匹配的文件名。只要程序需要查找文件系统中名字与某个模式匹配的一组文件,就可以使用这个模块。
glob的模式规则与re模块使用的正则表达式不相同。glob模式遵循标准UNIX路径扩展规则。只是用几个特殊字符来实现两个不同的通配符和字符区间。模式规则要应用于文件名中的段。模式中的路径可以是相对路径或绝对路径。
shell变量名和波浪线都不会扩展。

基本用法

1.glob.glob(pathname), 返回所有匹配的文件路径列表。它只有一个参数pathname,定义了文件路径匹配规则,这里可以是绝对路径,也可以是相对路径。
2.glob.iglob(pathname), 获取一个可编历对象,使用它可以逐个获取匹配的文件路径名。与glob.glob()的区别是:glob.glob同时获取所有的匹配路径,而glob.iglob一次只获取一个匹配路径。

3.eg:

import glob 
 
print glob.glob(r'E:\*\*.doc') 
print glob.glob(r'.\*.py') 
 
f = glob.iglob(r'.\*.py') 
 
for py in f: 
  print py 

运行结果:

['E:\\test_file\\adplus.doc'] 
['.\\perfrom_test.py', '.\\pyTest.py', '.\\simulation_login.py', '.\\widget.py', '.\\__init__.py'] 
.\perfrom_test.py 
.\pyTest.py 
.\simulation_login.py 
.\widget.py 
.\__init__.py 

下面我们分知识点详细来讲:


通配符
星号匹配一个文件名段中的0个或多个字符。

import glob
for name in glob.glob('tmp/*'):
  print name

这个模式会匹配所有的路径名,但是不会递归搜索到子目录。

>>> ================================ RESTART ================================
>>> 
tmp\checklog_status.sh
tmp\check_Adwords_v1.2.sh
tmp\check_traffic.sh
tmp\cut_nginxlog_V1.2.sh
tmp\ip_conn.sh
tmp\ip_keepalive.sh
tmp\nagios使用手册.doc
tmp\nmap_ping
tmp\nrpe_install-1.3.sh
tmp\one
tmp\syn.sh
tmp\zabbix_agentd_2.0.10_win_V1.2.bat
tmp\zabbix_agentd_2.0.8_V1.3.sh
tmp\工作内容.doc

要列出子目录中的文件,必须把子目录包含在模式中。

import glob
print 'Name explicitly:'
for name in glob.glob('tmp/one/*'):
  print '\t', name
print 'Name with wildcard:'
for name in glob.glob('tmp/*/*'):
  print '\t', name 

第一种情况显示列出子目录名,第二种情况则依赖一个通配符查找目录。

>>> ================================ RESTART ================================
>>> 
Name explicitly:
  tmp/one\another.txt
  tmp/one\file.txt
Name with wildcard:
  tmp\one\another.txt
  tmp\one\file.txt


单字节通配符
问号会匹配文件名中该位置的单个字符。

import glob
for name in glob.glob('tmp/chec?_traffic.sh'):
  print name
>>> ================================ RESTART ================================
>>> 
tmp\check_traffic.sh

   

字符区间
使用字符区间([a-z]),可以匹配多个字符中的一个字符。

import glob
for name in glob.glob('tmp/one/[a-z]*'):
  print name

区间可以匹配所有小写字母。   

>>> ================================ RESTART ================================
>>> 
tmp/one\another.txt
tmp/one\file.txt

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 are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools