#!/usr/bin/env python # -*- coding: UTF-8 -*- # Edit by ZeroC # 偷懒-生成python文件头信息 # AutoCreateHead.py import datetime import os import platform import getpass # *****查看文件是否存在***** # 判断目录是否存在,是否有可访问权限 def diraccess(dirname): # 目录不存在 disexists = -2 # 目录无访问权限,有权限为7 isaccess = -7 if os.path.exists(dirname): if not os.access(dirname, os.W_OK): return isaccess else: isaccess = 7 return isaccess else: return disexists # *****目录处理***** # 把路径转化为列表--list(); # 列表最后添加元素--append(); # 把列表转换成字符串--''.join() def formatdir(dirname = os.path.abspath('.')): if platform.system() == 'Linux': if dirname.endswith('/'): return dirname else: # 路径后添加/ listdir = list(dirname) listdir.append('/') return "".join(listdir) elif platform.system() == 'Windows': if dirname.endswith('\\'): listdir = list(dirname) listdir.append('\\') return ''.join(listdir) else: return dirname.rstrip('\\') # *****文件命名***** # 如果flag为1,文件名为filenam当前时间.py; # 如果flag为0,文件名为filenam_num.py # 当flag为0时,验证文件是否存在,并更换 def createfile(dirname ,filename = 'ZeroC' ,flag=0 , num = 1 ): dname = formatdir(dirname) if flag == 1: time_now = datetime.datetime.now().strftime('%Y%m%d%H%M%S') fname = dname + filename + '_' + time_now + '.py' return fname elif flag == 0: while True: fname = dname + filename + '_' + str(num) + '.py' daccess = diraccess(dname) if daccess == 7: if os.path.exists(fname): print("The file %s exists!" % fname) num += 1 else: break elif daccess == -7: print("You Deny !") chd = raw_input("Change other dir?[y:yes n:no]") if chd == 'y': Dname = raw_input("The Dirname:") dir = formatdir(Dname) createfile(dir,fname,0,1) else: print("You Deny ! Fail to Create file !") exit() elif daccess == -2: os.makedirs(dname) createfile(dname,fname,0,1) return fname # *****插入python文件前端公共部分***** def inserthead(fn): _user = getpass.getuser() _host = platform.node() _time = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M') if platform.system() == 'Linux': with open(fn,'a') as f: f.write('#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n') f.write('#Edit by %s on Linux\n#Hostname:%s\n#Time:%s\n#File:%s' % (_user, _host, _time,fn)) elif platform.system() == 'Windows': with open(fn,'a') as f: f.write('#!/usr/bin/env python\n\n# coding:utf-8\n') f.write('#Edit by %s on windows\n#Hostname: %s\n#Time:%s\n#File:%s' % (_user, _host, _time, fn)) if __name__ == '__main__': d = '/root/Python/test/' f = 't' fN = createfile(d,f,0,1) inserthead(fN)