Python Learning notes Glob module

Source: Internet
Author: User
Tags glob

Python has a number of class libraries, which are now documented for later review:

1.glob Module

For file name operations, matching files in the specified directory, there are two commonly used functions:

Glob (pattern), which returns a list of matching files.

Iglob (pattern), which returns the generator, can traverse the matching file.

Example code:

Glob ()
Bogon:datasets xuguoqiang$ lsmatrixA.txt matrixB.txt test words.txtfiles= Glob.glob ('*.txt')>>> forFileinchFiles: ...PrintFilematrixA.txtmatrixB.txtwords.txt>>>Printfiles['MatrixA.txt','MatrixB.txt','Words.txt']
 Iglob (): 
>>> files = Glob.iglob ( " *.txt ) >>> files <generator object Iglob at 0x1101d9dc0>>>> for file in files: ... print FilematrixA.txtmatrixB.txtwords.txt
Specify the result of a relative path
Import Glob Print Glob.glob (r'... /*.txt') ['.. /test.txt']

You can see that if pattern is specified as a relative path or an absolute path, the returned file is also a relative or absolute path. Use according to actual needs.

In addition, using the OS Listdir can also get similar results:

Import os>>> dir = r'./'print  os.listdir (dir) [' MatrixA.txt ' ' MatrixB.txt ' ' Test ' ' Words.txt ']

The difference is that Listdir will list all the filenames, including the folder, which contains no path and needs to be matched and filtered by itself.

Python Learning notes Glob module

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.