今天整理資料的時候,發現要在很多文件中的頭部和尾部添加相同的文本,於是自己使用Python做了一個簡單的文件拼接功能,也可以說是文件追加功能,給一個文件批量追加頭尾內容,達到省事的效果,順便還可以練習下Python。下面來介紹下:
現在有三個文件,如下:
- content.txt 位於一個叫path的文件中;
- header.txt用於添加到content.txt頭部的文件;
- footer.txt用於添加到content.txt尾部的文件。
現在要實現的功能就是,將header和footer分別添加到content的頭部和尾部。
函數說明:
- add_footer(infile, outfile):用於將footer內容添加到content中,第一個參數表示的添加到尾部的文件,如輸入footer.txt,第二個爲內容文件。如content.txt文件
- add_header(infile, outfile, auto=True): 用於將一個文件放入好另一個文件的頭部,如果auto=Ture,則不對內容做修改,auto爲False的話,這裏添加了部分需要的東西,如文件的創建時間、標題等信息。
- addHeadAndFooter(path, header, footer, auto=False):核心函數,調用頭尾兩個方法,此處的path爲文件夾名稱,該函數的功能是將path文件夾下的所有文件都添加頭和尾的內容,auto默認爲False,功能和上面的相同。
- getStdTime(seconds):將時間戳格式的日期轉換爲標準格式,如:2015-11-03 10:24
代碼(AddHeader.py):
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 03 10:32:26 2015
@author: liudiwei
"""
import os,time
def add_footer(infile, outfile):
with open(infile,'r') as inputfile:
with open(outfile,'a') as outfile:
outfile.write("\n\n"+''.join(inputfile.readlines()))
#如果auto==True,直接將文件內容加入到當前文件
def add_header(infile, outfile, auto=True):
inf=open(infile,'r')
outf = open(outfile,'r')
header = inf.readlines()
content=outf.readlines()
if auto==True:
with open(outfile,'w') as output:
output.write(''.join(header)+ "\n\n" \
+''.join(content))
else:
ctime=getStdTime(os.path.getctime(outfile))
title="title: " + outfile.split('/')[1].split('.')[0]
print title
add_content="---\n"
add_content=add_content+title+'\n' #add title
add_content=add_content+ctime +'\n' #add date
add_content=add_content+''.join(header)
with open(outfile,'w') as output:
output.write(''.join(add_content)+ "\n\n" \
+''.join(content))
outf.close()
inf.close()
def addHeadAndFooter(path, header, footer, auto=False):
filelist=os.listdir(path)
for eachfile in filelist:
add_header(header,path + "/" + eachfile, auto)
add_footer(footer,path + "/" + eachfile)
def getStdTime(seconds):
x = time.localtime(seconds)
return "date: "+ time.strftime('%Y-%m-%d %H:%M:%S',x)
if __name__=='__main__':
if (len(os.sys.argv)<4):
raise TypeError()
else:
print "os.sys.arg"
#path="path"
#header="head.md"
#footer="footer.md"
os.chdir(".")
path=os.sys.argv[1]
print path
header=os.sys.argv[2]
footer=os.sys.argv[3]
filelist=os.listdir(path)
addHeadAndFooter(path,header,footer)
print "Success added!"
#----------------
# command
# python AddHead.py "path" "header.txt" "footer.txt"
#----------------
直接在console控制檯上運行下列代碼即可
python AddHeader.py "path" "header.txt" "footer.txt"
此文乃博主即興之作,如果你從中有所收穫,歡迎前來贊助,爲博主送上你的支持:【贊助中心】。
個人博客: 【D.W BLOG】
新浪微博: 【@拾毅者】