今天用Python提取了Linux內核源代碼的目錄樹結構,沒有怎么寫過腳本程序,我居然折騰了2個小時,先是如何枚舉出給定目錄下的所有文件和文件夾,os.walk可以實現列舉,但是os.walk是只給出目錄名和文件名,而沒有絕對路徑。使用os.path.listdir可以達到這個目的,然后是創建目錄,由于當目錄存在是會提示創建失敗的錯誤,所以我先想刪除所有目錄,然后再創建,但是發現還是有問題,最好還是使用判斷如果不存在才創建目錄,存在時就不創建,貼下代碼:
# @This script can be used to iterate the given directory,and create the # empty directory structure without file in it,e.g,I want to have you directory # as the linux kernel source, but i don't want the files, then this script comes. # @This script is running under python 3.1 # @author:zhangchao # @Time:2011年7月25日18:43:26 ########################################################################### import os import re #listmydirs is created to recursivly list all the entrys in the specified path. #In fact, we have os.walk to handle this problem # #level:目錄的層數,不要也可以,主要是為了顯示目錄在那一層 #srcpath:內核源代碼所在的路路徑 #destpath:將要生成的內核源代碼的目錄結構所在路徑 # def createkerneldirs(level,srcpath,destpath): for entrys in os.listdir(srcpath): #學習listdir函數的用法 tmpsrcpath=srcpath+os.sep+entrys tmpdestpath = tmpsrcpath.replace(srcpath,destpath)#將源路徑中的E:\linux-2.6替換為E:\tmp,學習字符串替換函數的用法 print('in level:'+str(level)) print(tmpsrcpath) print(tmpdestpath) if os.path.isdir(tmpsrcpath): listmydirs(level+1,tmpsrcpath,tmpdestpath) if os.path.exists(tmpdestpath)==False: #如果文件不存在才創建文件 os.makedirs(tmpdestpath) if __name__=='__main__': #將E:\linux-2.6的內核源代碼目錄結構拷貝到E:\tmp目錄下 createkerneldirs(1,r'E:\linux-2.6',r'E:\tmp')
以上就是小編為大家帶來的Python提取Linux內核源代碼的目錄結構實現方法全部內容了,希望大家多多支持腳本之家~
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
