Home > Web Front-end > JS Tutorial > body text

How to use the glob module to find file paths in Python_Basic knowledge

WBOY
Release: 2016-05-16 15:54:25
Original
2754 people have browsed it

The glob module is one of the simplest modules with very little content. Use it to find file pathnames that match specific rules. It is similar to using file search under Windows. Only three matching characters are used to find files: "*", "?", "[]". "*" matches 0 or more characters; "?" matches a single character; "[]" matches characters within the specified range, such as: [0-9] matches numbers.
glob.glob

Returns a list of all matching file paths. It has only one parameter pathname, which defines the file path matching rules. It can be an absolute path or a relative path. Here is an example using glob.glob:

import glob
 
#获取指定目录下的所有图片
print glob.glob(r"E:/Picture/*/*.jpg")
 
#获取上级目录的所有.py文件
print glob.glob(r'../*.py') 
#相对路径
Copy after login
glob.iglob

Get a calendarable object, which can be used to obtain matching file path names one by one. The difference with glob.glob() is that glob.glob obtains all matching paths at the same time, while glob.iglob only obtains one matching path at a time. This is somewhat similar to the DataSet and DataReader used in .NET to operate databases. Here is a simple example:

import glob
 
#父目录中的.py文件
f = glob.iglob(r'../*.py')
 
print f 
#<generator object iglob at 0x00B9FF80>
 
for py in f:
  print py
Copy after login

It's so easy, is't it?

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!