[問題] 找資料夾子目錄關鍵字,並將完整路徑寫進

看板Python作者 (KS)時間5年前 (2020/05/27 10:56), 編輯推噓3(307)
留言10則, 3人參與, 5年前最新討論串1/1
程式碼如下 希望把192.111那個路徑底下的txt檔完整路徑都讀到test.txt內 路徑底下檔案實在太多.....趴得很辛苦 請問各位高手有沒有更快的方式可以達到相同效果 ------------------------ import os # get .txt document rootdir=os.path.join('//192.111.235.33/test_read') # rootdir=os.path.join('D:\Darren_Hsu\Desktop\PY_TEST') # read write_path=open('D:\test_hsu\Desktop\PY_TEST\TEST.txt','w') for (dirpath,dirnames,filenames) in os.walk(rootdir): for filename in filenames: if os.path.splitext(filename)[1]=='.txt' and '20200501' in filename : write_path.write(dirpath+filename+'\n') write_path.close() ----- Sent from JPTT on my OnePlus IN2020. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.76.71.114 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1590548197.A.C48.html

05/27 13:02, 5年前 , 1F
你是使用 python2 ? 早期 python2 跑 os.walk() 慢
05/27 13:02, 1F

05/27 13:03, 5年前 , 2F
若你是使用 python3.5 開始版本應該改善不少
05/27 13:03, 2F

05/27 13:04, 5年前 , 3F
在我系統上相同 os.walk() 在 python3.6 比 2.7 快 3 倍
05/27 13:04, 3F

05/27 13:05, 5年前 , 4F
另外你用 windows 路徑應該用 r'D:\test' 這類避免異常
05/27 13:05, 4F

05/27 13:14, 5年前 , 5F

05/27 13:15, 5年前 , 6F
3.5 開始提供 os.scandir, 而 os.walk 實作這樣呼叫
05/27 13:15, 6F

05/27 14:28, 5年前 , 7F
直接用 pathlib
05/27 14:28, 7F

05/27 14:30, 5年前 , 8F
pathlib.Path(dirpath).rglob('*.txt')
05/27 14:30, 8F

05/27 17:28, 5年前 , 9F
pathlib超讚
05/27 17:28, 9F

05/27 20:36, 5年前 , 10F
pathlib處理掃描列列表用os.scandir,有glob支援的確省事
05/27 20:36, 10F
文章代碼(AID): #1UpTRbn8 (Python)
文章代碼(AID): #1UpTRbn8 (Python)