python 遍曆檔案夾

來源:互聯網
上載者:User

標籤:sed   targe   檔案的   ftp   ref   htm   link   pdo   --   

參考部落格:http://www.cnblogs.com/lincj/p/5617605.html

一、os.walk() 

  os.walk(top, topdown=True, onerror=None, followlinks=False) 

  可以得到一個三元tupple(dirpath, dirnames, filenames), 

  第一個為起始路徑,第二個為起始路徑下的檔案夾,第三個是起始路徑下的檔案。

  dirpath 是一個string,代表目錄的路徑,

  dirnames 是一個list,包含了dirpath下所有子目錄的名字。

  filenames 是一個list,包含了非目錄檔案的名字。

  這些名字不包含路徑資訊,如果需要得到全路徑,需要使用os.path.join(dirpath, name)

 

二、枚舉檔案夾下所有檔案
import os# 枚舉dirPath目錄下的所有檔案def main(dirname):    # begin    for root, dirs, files in os.walk(dirname):        print(root)        print(dirs)        print(files)        for dir in dirs:            print(os.path.join(root, dir))        for file in files:            print(os.path.join(root, file))        print(‘----------------‘)if __name__ == ‘__main__‘:    main(r‘G:\ftp\home\bigberg‘)

   

三、遍曆檔案夾擷取大小 
def get_used_size(dirname):    """        遍曆檔案夾擷取檔案大小    """    size = 0    for dir_path, dirs, files in os.walk(dirname):        # size += sum([os.path.getsize(os.sep.join([dir_path, name])) for name in files])        for name in files:            size += os.path.getsize(os.sep.join([dir_path, name]))    return size

  

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.