python 提取目錄中特定型別的檔案

2021-09-29 05:13:53 字數 1422 閱讀 7556

python使用『os』和『re』模組提取目錄中特定型別的檔案,這兩個模都是安裝python自帶的,所以不需要安裝。

思路:

使用os庫lilstdir獲取資料夾中的所有檔名,然後帶上資料夾路徑組合成為完整絕對路徑,然後去判斷該路徑檔案的型別,如果是檔案,使用re庫正則相關函式去篩選出特定字尾的檔案;如果是資料夾,遞迴處理此資料夾。

注意:

下面**提取的是『xlsx』檔案,如果需要提取其他型別的檔案,替換re.complie('str')中的正規表示式即可。

原始碼:

import

osimport

refilelist =

#function can get *.xls/*.xlsx file from the directory

"""dirpath: str, the path of the directory

"""def

_getfiles(dirpath):

#open directory

files =os.listdir(dirpath)

#re match *.xls/xlsx,you can change 'xlsx' to 'doc' or other file types.

ptn = re.compile('

.*\.xlsx')

for f in

files:

#isdir, call self

if (os.path.isdir(dirpath + '

\\' +f)):

getfiles(dirpath + '

\\' +f)

#isfile, judge

elif (os.path.isfile(dirpath + '

\\' +f)):

res =ptn.match(f)

if (res !=none):

\\' +res.group())

else

:\\無效檔案')

#function called outside

"""dirpath: str, the path of the directory

"""def

getfiles(dirpath):

_getfiles(dirpath)

return

filelist

if__name__ == "

__main__":

path = '

d:\\pyfiles\\test

'res =getfiles(path)

print('

提取結果:')

for f in

res:

print(f)

python提取txt中的特定字元工具

由於工作需要需要提取乙個txt檔案中的特定字元 原始檔案結構如下 logon name xiaoming display name 中國小明 user password 123 org name logon name xiaohuang display name 中國小黃 user password...

Python中刪除特定目錄下的檔案

widnows中的指令碼不好用,所以投向python,用python協助工作,很好 import os,sys from stat import import shutil delpathname urelease def walktree top,callback for f in os.list...

用 Python 定位特定型別檔案

定位特定檔案 定位特定的檔案,可以使用 fnmatch 以及 glob 這兩個標準庫,我們下面來分別看一下。1.使用 fnmatch 標準庫 一般的話我們想要查詢特定型別的檔案,可以通過字串的字首匹配和字尾匹配來查詢,具體例項如下所示 import os txt for txt in os.list...