作者taiwanbeers (KS)
看板Python
標題[問題] 找資料夾子目錄關鍵字,並將完整路徑寫進
時間Wed May 27 10:56:24 2020
程式碼如下
希望把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
→ kenduest: 你是使用 python2 ? 早期 python2 跑 os.walk() 慢 05/27 13:02
→ kenduest: 若你是使用 python3.5 開始版本應該改善不少 05/27 13:03
→ kenduest: 在我系統上相同 os.walk() 在 python3.6 比 2.7 快 3 倍 05/27 13:04
→ kenduest: 另外你用 windows 路徑應該用 r'D:\test' 這類避免異常 05/27 13:05
→ kenduest: 3.5 開始提供 os.scandir, 而 os.walk 實作這樣呼叫 05/27 13:15
推 vvind: 直接用 pathlib 05/27 14:28
推 vvind: pathlib.Path(dirpath).rglob('*.txt') 05/27 14:30
推 TitanEric: pathlib超讚 05/27 17:28
→ kenduest: pathlib處理掃描列列表用os.scandir,有glob支援的確省事 05/27 20:36