Python glob使用 返回檔案路徑

2021-08-18 14:07:18 字數 1738 閱讀 9097

glob是python自己帶的乙個檔案操作相關模組,用它可以查詢符合自己目的的檔案,類似於windows下的檔案搜尋,支援萬用字元操作,,?,這三個萬用字元,代表0個或多個字元,?代表乙個字元,匹配指定範圍內的字元,如[0-9]匹配數字。兩個主要方法如下。

1. glob方法:

glob模組的主要方法就是glob,該方法返回所有匹配的檔案路徑列表(list);該方法需要乙個引數用來指定匹配的路徑字串(字串可以為絕對路徑也可以為相對路徑),其返回的檔名只包括當前目錄裡的檔名,不包括子資料夾裡的檔案。

比如:glob.glob(r』c:*.txt』)

我這裡就是獲得c盤下的所有txt檔案

獲得指定目錄下的所有jpg檔案

使用相對路徑:

glob.glob(r』../*.py』)

2. iglob方法:

獲取乙個迭代器( iterator )物件,使用它可以逐個獲取匹配的檔案路徑名。與glob.glob()的區別是:glob.glob同時獲取所有的匹配路徑,而 glob.iglob一次只獲取乙個匹配路徑。下面是乙個簡單的例子:

#父目錄中所有的.py檔案

f = glob.iglob(r'../*.py')

print f

0x00b9ff80>

for py in f:

print py

f是乙個迭代器物件,通過遍歷,可以輸出所有滿足條件的*.py檔案

官方說明:

glob.glob(pathname)

return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/python-1.5/makefile) or relative (like and can contain shell-style wildcards. broken symlinks are included in the results (as

in the shell).

glob.iglob(pathname)

return an iterator which yields the same values as glob() without actually storing them all simultaneously.

new in version 2.5.

for example, consider a directory containing only the following files: 1.gif, 2.txt, andcard.gif. glob() will produce the following results. notice how any leading components of the path are preserved.

>>> 

import glob

>>> glob.glob('./[0-9].*')

['./1.gif', './2.txt']

>>> glob.glob('*.gif')

['1.gif', 'card.gif']

>>> glob.glob('?.gif')

['1.gif']

p

MVC返回檔案

1.response返回檔案 在mvc的專案中,還是能看到很多同事,喜歡使用 response的方式來返回檔案.如 雖然這種方式確實可以返回檔案,但是在mvc中,提供了乙個簡便的方法.可以把檔案作為返回值去返回.2.fileresult public actionresult get 返回檔案的時候...

mysql 返回 文件 mysql

首先要宣告一下 一般情況下,修改mysql密碼,授權,是需要有mysql裡的root許可權的。測試環境 win32 mysql5.0.45 注 本操作是在win命令提示符下,phpmyadmin同樣適用。使用者 phplamp 使用者資料庫 phplampdb 1.新建使用者。登入mysql mys...

返回檔案流 使用流讀取檔案內容

程式 public static void fis catch exception e 程式執行結果 通過開啟乙個到實際檔案的連線來建立乙個 fileinputstream,該檔案通過檔案系統中的 file 物件 file 指定。通過使用檔案描述符 fdobj 建立乙個 fileinputstrea...