python walk曆遍目錄

來源:互聯網
上載者:User

標籤:最大   tiff   檔案大小   div   os.walk   port   enumerate   res   lam   

import os
import fnmatch


def is_file_match(filename, patterns):
for pattern in patterns:
if fnmatch.fnmatch(filename, pattern):
return True
return False


def find_specific_files(root, patterns=[‘*‘], exclude_dir=[]):
for root, dirnames, filenames in os.walk(root):
for filename in filenames:
if is_file_match(filename, patterns):
yield os.path.join(root, filename):
for d in exclude_dir:
if d in dirnames:
dirnames.remove(d)

#尋找目錄下所有檔案
for item in find_specific_files(‘.‘)
print(item)

#尋找目錄下所有圖片
patterns = [‘*.jpg‘,‘*.jpeg‘,‘*.png‘,‘*.tif‘,‘*.tiff‘]
for item in find_specific_files(‘.‘,patterns)
print(item)

#尋找分類樹中,除dir2目錄以為其他目錄下的所有圖片
patterns1 = [‘*.jpg‘,‘*.jpeg‘,‘*.png‘,‘*.tif‘,‘*.tiff‘]
exclude_dirs = [‘dir2‘]
for item in find_specific_files(‘.‘,patterns1,exclude_dirs):
print(item)

#尋找目錄下最大的十個檔案,find_specific_files已經能找到某個目錄下的所有檔案,只要擷取檔案大小並按大小排序,輸出最大的十個檔案即可
files = {name:os.path.getsize(name) for name in find_specific_files(‘.‘)}
result = sorted(files.items(),key=lambda d:d[1],reverse=True)[:10]
for i in enumerate(result,1):
print(i,t[0],t[1])

python walk曆遍目錄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.