[python]使用Glob()查找文件


https://docs.python.org/3.6/library/glob.html

 

大多Python函數有着長且具有描述性的名字。但是命名為glob()的函數你可能不知道它是干什么的除非你從別處已經熟悉它了。
它像是一個更強大版本的listdir()函數。它可以讓你通過使用模式匹配來搜索文件。

import glob
 
# get all py files
files = glob.glob('*.py')
print files
 
# Output
# ['arg.py', 'g.py', 'shut.py', 'test.py']

  你可以像下面這樣查找多個文件類型:

import itertools as it, glob
 
def multiple_file_types(*patterns):
    return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns)
 
for filename in multiple_file_types("*.txt", "*.py"): # add as many filetype arguements
    print filename
 
# output
#=========#
# test.txt
# arg.py
# g.py
# shut.py
# test.py

  如果你想得到每個文件的絕對路徑,你可以在返回值上調用realpath()函數:

import itertools as it, glob, os
 
def multiple_file_types(*patterns):
    return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns)
 
for filename in multiple_file_types("*.txt", "*.py"): # add as many filetype arguements
    realpath = os.path.realpath(filename)
    print realpath
 
# output
#=========#
# C:\xxx\pyfunc\test.txt
# C:\xxx\pyfunc\arg.py
# C:\xxx\pyfunc\g.py
# C:\xxx\pyfunc\shut.py
# C:\xxx\pyfunc\test.py

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM