python檔案操作之目錄遍曆執行個體分析

來源:互聯網
上載者:User
本文執行個體講述了python檔案操作之目錄遍曆的方法。分享給大家供大家參考。具體分析如下:

Python的os模組,包含了普遍的作業系統功能,這裡主要學習與路徑相關的函數:

os.listdir(dirname):列出dirname下的目錄和檔案
os.getcwd():獲得當前工作目錄
os.curdir:返回目前的目錄('.')
os.chdir(dirname):改變工作目錄到dirname
os.path.isdir(name):判斷name是不是一個目錄,name不是目錄就返回false
os.path.isfile(name):判斷name是不是一個檔案,不存在name也返回false
os.path.exists(name):判斷是否存在檔案或目錄name
os.path.getsize(name):獲得檔案大小,如果name是目錄返回0
os.path.abspath(name):獲得絕對路徑
os.path.normpath(path):規範path字串形式
os.path.split(name):分割檔案名稱與目錄(事實上,如果你完全使用目錄,它也會將最後一個目錄作為檔案名稱而分離,同時它不會判斷檔案或目錄是否存在)
os.path.splitext():分離檔案名稱與副檔名
os.path.join(path,name):串連目錄與檔案名稱或目錄
os.path.basename(path):返迴文件名
os.path.dirname(path):返迴文件路徑

1、os.path方法

通過傳入需要遍曆的目錄,列出目錄下的所有檔案並統計檔案數,os提供的path模組能對目錄非常靈活的操作。

import os,sysdef listdir(dir,file):  file.write(dir + '\n')  fielnum = 0  list = os.listdir(dir) #列出目錄下的所有檔案和目錄  for line in list:    filepath = os.path.join(dir,line)    if os.path.isdir(filepath): #如果filepath是目錄,則再列出該目錄下的所有檔案      myfile.write('  ' + line + '\\'+'\n')      for li in os.listdir(filepath):        myfile.write('   '+li + '\n')        fielnum = fielnum + 1    elif os.path:  #如果filepath是檔案,直接列出檔案名稱      myfile.write('  '+line + '\n')       fielnum = fielnum + 1  myfile.write('all the file num is '+ str(fielnum))dir = raw_input('please input the path:')myfile = open('list.txt','w')

2、os.walk方法

os模組提供的walk方法很強大,能夠把給定的目錄下的所有目錄和檔案遍曆出來。
方法:os.walk(path),遍曆path,返回一個對象,他的每個部分都是一個三元組,('目錄x',[目錄x下的目錄list],目錄x下面的檔案)

import osdef walk_dir(dir,fileinfo,topdown=True):  for root, dirs, files in os.walk(dir, topdown):    for name in files:      print(os.path.join(name))      fileinfo.write(os.path.join(root,name) + '\n')    for name in dirs:      print(os.path.join(name))      fileinfo.write(' ' + os.path.join(root,name) + '\n')dir = raw_input('please input the path:')fileinfo = open('list.txt','w')walk_dir(dir,fileinfo)

topdown決定遍曆的順序,如果topdown為True,則先列舉top下的目錄,然後是目錄的目錄,依次類推,反之,則先遞迴列舉出最深層的子目錄,然後是其兄弟目錄,然後子目錄。

希望本文所述對大家的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.