python源码提取_Python提取Linux内核源代码的目录结构实现方法
今天用Python提取了Linux內(nèi)核源代碼的目錄樹結(jié)構(gòu),沒有怎么寫過腳本程序,我居然折騰了2個(gè)小時(shí),先是如何枚舉出給定目錄下的所有文件和文件夾,os.walk可以實(shí)現(xiàn)列舉,但是os.walk是只給出目錄名和文件名,而沒有絕對(duì)路徑。使用os.path.listdir可以達(dá)到這個(gè)目的,然后是創(chuàng)建目錄,由于當(dāng)目錄存在是會(huì)提示創(chuàng)建失敗的錯(cuò)誤,所以我先想刪除所有目錄,然后再創(chuàng)建,但是發(fā)現(xiàn)還是有問題,最好還是使用判斷如果不存在才創(chuàng)建目錄,存在時(shí)就不創(chuàng)建,貼下代碼:
# @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:目錄的層數(shù),不要也可以,主要是為了顯示目錄在那一層
#srcpath:內(nèi)核源代碼所在的路路徑
#destpath:將要生成的內(nèi)核源代碼的目錄結(jié)構(gòu)所在路徑
#
def createkerneldirs(level,srcpath,destpath):
for entrys in os.listdir(srcpath): #學(xué)習(xí)listdir函數(shù)的用法
tmpsrcpath=srcpath+os.sep+entrys
tmpdestpath = tmpsrcpath.replace(srcpath,destpath)#將源路徑中的E:\linux-2.6替換為E:\tmp,學(xué)習(xí)字符串替換函數(shù)的用法
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: #如果文件不存在才創(chuàng)建文件
os.makedirs(tmpdestpath)
if __name__=='__main__':
#將E:\linux-2.6的內(nèi)核源代碼目錄結(jié)構(gòu)拷貝到E:\tmp目錄下
createkerneldirs(1,r'E:\linux-2.6',r'E:\tmp')
以上就是小編為大家?guī)淼腜ython提取Linux內(nèi)核源代碼的目錄結(jié)構(gòu)實(shí)現(xiàn)方法全部內(nèi)容了,希望大家多多支持腳本之家~
總結(jié)
以上是生活随笔為你收集整理的python源码提取_Python提取Linux内核源代码的目录结构实现方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux添加php到环境,Linux系
- 下一篇: linux命令查看磁盘使用情况,linu