python脚本-自动化处理文件 背景 最近在工作中遇到一个很麻烦的操作,我需要先修改xml表,然后运行一个程序,这个程序会根据xml表生成许多模板文件,我需要把被我影响到的几个文件还有新生成的两个文件拷到工作目录,然后把xml和一个特殊文件压缩。最后在生成的模板文件上进行开发。
内容 主要完成程序的执行,文件的批量复制,文件批量删除,执行shell命令等功能。 此脚本涉及到工作内容,所以有些关键信息,比如程序名,工作目录,文件名,我会进行相应的替换。
三个函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import osimport sysdef dir_isexists (): if not os.path.exists("./test" ): os.mkdir("./test" ) print "creat ./test" def cp_func (name ): for f in os.listdir("./test" ): if os.path.join("./test" ,f) == name: cmd = "cp -f {} ./app" .format (name) if os.system(cmd) == 0 : print "success cp {} to ./app" .format (name)def delet_file (): for f in os.listdir("./test" ): if os.path.isfile(os.path.join("./test" ,f)): os.remove(os.path.join("./test" ,f)) print "remove " + f os.rmdir("./test" ) print "rm ./test"
函数功能:
dir_isexists:判断使用程序时指定生成的模板文件存放的路径是否存在,如不存在就创建
cp_func:将需要的文件拷贝到工作目录
delet_file:删除没有用的模板文件 关于os库和sys库可以参考python标准库-os ,python标准库-sys
主函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 if __name__ == "__main__" : if len (sys.argv) < 2 : print "please input a nodename" sys.exit(0 ) if not os.path.exists("./tools" ): print "please go to ******" sys.exit(0 ) filename_c = "./test/device_" + sys.argv[1 ] + ".c" filename_h = "./test/device_" + sys.argv[1 ] + ".h" filename_com = "./test/******.h" filename_model = "./test//******..c" filename_id = "./test//******..h" filename_sort = "./test//******..h" filename_device_h = "./test//******..h" tar_dir = "./******/******/******/" gz_file = "******.tar.gz" xml_file = "******.xml" instance_file = "******" namelist = [] namelist.append(filename_c) namelist.append(filename_h) namelist.append(filename_com) namelist.append(filename_model) namelist.append(filename_id) namelist.append(filename_sort) namelist.append(filename_device_h) if os.path.isfile(os.path.join(tar_dir,xml_file)) and os.path.isfile(os.path.join(tar_dir,instance_file)): retval = os.getcwd() os.chdir(tar_dir) tar_cmd = "tar -czvf " + " " + gz_file + " " + xml_file + " " + instance_file if os.system(tar_cmd) != 0 : print "failure to tar, please tar by yourself" os.chdir(retval) dir_isexists() if os.system("./tools/****** -f ./******/******.xml -p ./test" ) != 0 : print "failure get node file" sys.exit(0 ) else : print "success get node file" for files in namelist: cp_func(files) delet_file()
主函数流程:
主函数开始会判断是否有参数,工作目录是否正确,判断工作目录是否正确的方式我采用了判断一个特殊路径是否存在,如果存在则说明工作目录正确
第二部分就是定义出我需要使用的文件,和新生成的文件(由提供的参数确定新生成的文件名),并放到列表中
判断xml文件是否存在,并将其压缩
执行工具程序生成模板文件
拷贝后删除生成文件
意义 主要熟悉os和sys库的基本操作