python筆記之按檔案名稱搜尋指定路徑下的檔案

來源:互聯網
上載者:User

標籤:work   分享圖片   sea   .sh   listdir   寫入   open   ret   cell   

1.搜尋檔案名稱中以指定的字串開頭(如搜尋dll,結果中含有dll a,dll abc等)

我的目錄下有dll a.txt和dll.txt檔案

 

其中a檔案夾下還有這兩個檔案

 

我希望通過python選擇尋找關鍵字dll來把這四個檔案找出


import os

result=[]
def search(path=".", name=""):
for item in os.listdir(path):
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
search(item_path, name)
elif os.path.isfile(item_path):
if name in item:
global result
result.append(item_path + ";")
print (item_path + ";", end="")

search(path=r"D:\newfile", name="dll")

 輸出結果:

 

2.如果我只想找出名叫dll的txt,不要dll a.txt,即上文是關鍵字匹配,這次改為全匹配。那麼就要用到搜尋指定的檔案名稱

 只要將上文代碼中

    if name in item:

  改為

     if name+".txt" == item:

  即可

 

3.提取excel某一列中病人姓名並轉化為拼音,根據拼音檢索某一路徑下的對應圖片路徑

# -*-coding:utf-8-*-import xlrdimport osimport refrom xlwt import *from xpinyin import Pinyinpa=NonemyItem_path = []def file_name(file_dir):    for root, dirs, files in os.walk(file_dir):        return(dirs) #當前路徑下所有非目錄子檔案def search(path=".", name="1"):    for item in os.listdir(path):        global pa        item_path = os.path.join(path, item)        if os.path.isdir(item_path):            search(item_path, name)            # if(t==None):pa=None        elif os.path.isfile(item_path):            if name+".jpg" == item:                        myItem_path.append(item_path+";")                        print (item_path+";",end="")                        pa=myItem_path#------------------讀資料--------------------------------fileName="D:\\study\\xmu\\420\\廖希一\\數字化之後\\上機名單-2014,2015.xls"bk=xlrd.open_workbook(fileName)shxrange=range(bk.nsheets)try:    sh=bk.sheet_by_name("2014年")except:    print ("代碼出錯")nrows=sh.nrows #擷取行數book = Workbook(encoding=‘utf-8‘)sheet = book.add_sheet(‘Sheet1‘) #建立一個sheetp = Pinyin()for i in range(1,nrows):    # row_data=sh.row_values(i)    #擷取第i行第3列資料    #    #---------寫出檔案到excel--------    # if i==16:    #     break    a=p.get_pinyin( sh.cell_value(i,2), ‘ ‘)    search(path=r"D:\study\xmu\420\廖希一\photo", name=a)    myItem_path=[]    print ("-----正在寫入 "+str(i)+" 行")    sheet.write(i,0, label = sh.cell_value(i,2)) #向第1行第1列寫入擷取到的值    sheet.write(i,1, label = sh.cell_value(i,4))#向第1行第2列寫入擷取到的值    sheet.write(i,2, label=a)    sheet.write(i,3, label=pa)    pa=Nonebook.save("D:\\study\\xmu\\420\\廖希一\\數字化之後\\上機名單-2014+圖片路徑.xls")

 

python筆記之按檔案名稱搜尋指定路徑下的檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.