python怎樣編寫 PYTHON怎樣編寫自動化

2021-10-11 12:14:21 字數 4677 閱讀 5469

匿名使用者

1級2018-09-18 回答

就直接寫指令碼,給你舉給例子:

編寫工具:

1.設計目標:

首先說一下我要工具的功能:

遍歷某個目錄下包括其下子目錄中所有指定的字尾檔案,然後為這些檔案的頭部插入指定的字串。

2.使用場景:

設計這樣的工具起因是我最近在將之前 csdn 中的部落格搬運到自己的 hexo 部落格空間上,了解的應該知道,假如都是 markdown 編寫的話,搬運的時候只需要在檔案頭部加上如下的一串額外的內容:

title: 部落格標題

date: 部落格建立時間(例如:2016-09-03 17:15:22)

tags: 標籤(如:[hexo,next],多個的話用,號隔開)

categories: 分類(如:web)

---123456

標題 title 直接使用檔名稱去掉 .md 字尾即可;

時間 date 需要通過檔案庫獲取檔案的建立時間;

標籤 tags 和分類 categories ,由於我的檔案會根據分類放入不同的子目錄下,所以直接獲取當前檔案所在目錄的名稱即可。

此外,為了在部落格首頁只展示部分內容,而不是展開部落格的完整內容,還需要在部落格中恰當的位置插入這個標籤: ,通常載入第一段內容結束的位置。

3.實現**:

根據上面的思路,我們在 source/_posts 目錄下建立乙個工具指令碼,起名為 suitfiletohexo.py ,然後依次完成以下步驟:

指定 linux 環境下 python 直譯器目錄,並指定編碼方式:

#!/usr/bin/env python# -*- coding: utf-8 -*-

引入的模組:

在指令碼開始的地方,最先需要做的事情就是把需要用到的模組都先引入進來,大致分析一下我們這個功能需要用到的模組:

import os.path,time

遍歷當前目錄下所有 .md 檔案列表:

這就需要使用到 python 的檔案目錄操作模組 os.path ,使用 os.listdir 獲取目錄列表,然後通過 os.path.splitext 分割檔名稱和字尾名,從而篩選合格的檔案:

# 獲取指定目錄指定字尾名的檔案列表def getfilelist(path,endstr):'''獲取指定目錄下,指定字尾的檔案列表'''r_list =

f_list = os.listdir(path)   #獲取目錄列表for i in f_list:    # 分離檔名和字尾名,過濾掉工具指令碼

file_endstr = os.path.splitext(i)[1]    # 判斷是否是目錄

if os.path.isdir(i):

f_list1 = os.listdir(path+'/'+i)        for j in f_list1:            # 過濾出指定字尾 endstr 字尾的檔案

if os.path.splitext(j)[1] == endstr:                # 為了清晰目錄把檔案所在目錄也標識出來

elif file_endstr == endstr:

這裡發現了乙個問題,就是在 os.path.isdir(i) 在 2.7.11 的版本莫名其妙地返回 false,需要做如下修改才能正常:

if file_endstr == '':

i = os.path.join(path, i)   #***************==〉這一行很必要

# print i

# 判斷是否是目錄

if os.path.isdir(i):

需要使用到 os.time 模組的功能:

# 獲取檔案建立時間def get_filecreatetime(filepath):

timestruct = time.localtime(timestamp)  return time.strftime('%y-%m-%d %h:%m:%s',timestruct)

其實就是從目錄字串中截掉字尾名,再截掉最後乙個 / 之前的內容即可得到部落格名稱:

# 獲取目錄中去掉前面路徑和字尾的檔案名字def getfile******name(filepath):

name = ''

# 先去掉字尾

name = os.path.splitext(filepath)[0]  # 獲取最後乙個斜槓位置

index = name.rfind('/')  # 找不到則返回 -1

if index != -1:  # 擷取斜槓後面到結尾內容

name = name[index+1:]  # print name

return name

獲取檔案所在的目錄名稱作為頁籤值:

與獲取部落格名稱思路略有相似,獲取最後乙個斜槓位置,截掉斜槓之後的內容,在獲取乙個最後乙個斜槓位置,假如有則擷取斜槓之後的內容即是檔案所在目錄的名稱:

# 獲得分類檔案目錄名稱def gettypenamebypath(filepath):filetag = ''# 獲取最後乙個斜槓位置index = filepath.rfind('/')# 找不到則返回 -1if index != -1:    # 擷取斜槓後面到結尾內容

filetag = filepath[:index]    # 截掉前面部分

index = filetag.rfind('/')    if index != -1:

filetag = filetag[index+1:]# print filetagreturn filetag

向檔案中插入內容:

呼叫以上方法即可分別得到我們想要的資訊:

# 指定目錄path = './'# 得到檔案列表files = getfilelist(path,'.md')

for i in files:  print 'title: '+getfile******name((i.decode("string_escape")))  print 'date: '+get_filecreatetime((path+i.decode("string_escape")))  print 'tags: ['+gettypenamebypath((i.decode("string_escape")))+']'

接下來要做的就是把這些內容按照格式插入到檔案中去,當然插入之前需要先檢查檔案中是否已經插入過類似的內容了,可以簡單地通過檢查開頭 40 個字串中是否包含這個字串來判別:

title: '''

關於展示分隔符  插入的位置,大致邏輯是:第乙個標題後面,而且剛好插入在第二個標題之前即可,而使用 markdown 語法撰寫的部落格標題使用 # 來表示的,最終的插入方法如下:

# 向檔案中插入指定資料def addheadtofile(filepath,title,date,tags):file = open(filepath,"r")

content = file.read()

index = content[:40].find('''---

title:''')# 新增if index == -1:    print 'undadded'

addcontent = '''---

title: '''+title+'''

date: '''+date+'''

tags: ['''+tags+''']

categories: '''+tags+'''

# 檢測是否插入部分顯示標籤

content = addcontent + content

index = content.find(''' ''')    if index == -1:        # 獲取第一段的位置

index = content.find('''### ''')        if index != -1:            #print "first ### pos = ",index

# 下乙個標題位置(在第二個標題之前插入即可)

pos = content[index:].find('''

#''',1)            if pos != -1:

index += pos                #print "second enter pos = ",index

content = content[:index]+'''

'''+content[index:]

file = open(filepath,"w")

file.write(content)else:    #print 'file head had added'# 記得要關閉檔案file.close()

最後完整的呼叫過程:

# 指定目錄path = './'# 得到檔案列表files = getfilelist(path,'.md')

# 宣告一些全域性變數title = ''date = ''tags = ''for i in files:

title = getfile******name(i.decode("string_escape"))

date = get_filecreatetime(path+i.decode("string_escape"))

tags = gettypenamebypath(i.decode("string_escape"))    print 'title: '+title    print 'date: '+date    print 'tags: ['+tags+']'

addheadtofile(path+i.decode("string_escape"),title,date,tags)

SublimeText工具編寫 Python

sublimetext python 方法 步驟 開啟sublimetext 在選單欄找到tools 編譯系統 新編譯系統 使用sublimetext 作為python 的開發環境 使用sublimetext 作為python 的開發環境 在新的配置檔案中輸入如下配置 cmd u file file...

python 怎樣匯入其他地方的python模組

sys.path是python的搜尋模組的路徑集,是乙個list。1 臨時新增,在乙個shell視窗中 py檔案存放在f python資料夾下 使用下面方法將路徑永久新增到sys.path 2 使用pth檔案永久新增 使用pth檔案,在 site packages 檔案中建立 pth檔案,將模組的路...

初識python,編寫乙個簡單的python程式

在ubuntu下安裝好了最新的python3.9,開啟學習python之旅。在命令列輸入python進入互動模式 互動模式下,你每輸入一行 python直譯器就將這一行 轉換成機器碼來執行。例如 互動模式輸入100 200,然後回車 直接會顯示執行結果300 但是這樣的 是沒有儲存的,如果下次我們還...