python 掃描目錄下所有檔案並讀取檔案__python

來源:互聯網
上載者:User

先介紹兩個函數:

一。os.walk()可以得到一個三元tupple(dirpath,sub_dirs, filenames),其中第一個為起始路徑,第二個為起始路徑下的檔案夾,第三個是起始路徑下的檔案。
其中dirpath是一個string,代表目錄的路徑,sub_dirs是一個list,包含了dirpath下所有子目錄的名字。filenames是一個list,包含了非目錄檔案的名字。這些名字不包含路徑資訊,如果需要得到全路徑,需要使用os.path.join(dirpath, name).

二。withopen(spcial_file_dir)assource_file

with 語句是在 Python 2.5 版本引入的,從 2.6 版本開始成為預設的功能。

with 語句作為 try/finally 編碼範式的一種替代,用於對資源訪問進行控制的場合。

如果要開啟檔案並保證最後關閉他,只需要這麼做:

withopen("x.txt") as f:    data=f.read()    do something with data

with-as運算式極大的簡化了每次寫finally的工作,無需自己手動將開啟檔案close()掉 若要更深理解: http://zhoutall.com/archives/325
http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/ 掃描目錄讀取檔案,不考慮子目錄情況

try:    source_dir = '/dir/source/'    target_dir = '/dir/old/'    for root, sub_dirs, files in os.walk(source_dir):        for special_file in files:            spcial_file_dir = os.path.join(root, special_file)            # 開啟檔案的兩種方式            # 1.檔案以絕對路徑方式            with open(spcial_file_dir) as source_file:            # 2.檔案以相對路徑方式            # with open(r'dir_test/test.txt') as source_file:                for line in source_file:                    # do something            # 移動檔案            shutil.move(spcial_file_dir, target_dir)            logger.info(u'檔案%s移動成功'% spcial_file_dir)    return HttpResponse(json.dumps({'result':0}))except Exception as e:    # do something


聯繫我們

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