【Python脚本】实现修改文件内容、添加并保存

# -*- coding: utf-8 -*-
#coding=utf-8
import os
import os.path
import sys
import string
import re

path1 = os.getcwd()
for parent,dirnames,filenames in os.walk('.'):			
	for dirname in dirnames:
		if os.path.isdir(dirname):
			print(dirname)
			os.chdir(dirname)
			line_new = open("config_new.h",'w+')
			line_file = open("config.h",'r+')
			for line in line_file:
				if "#define	DEFAULT_SUPPORT_OSD_LANGUAGE_Uzbek" in line:
					line = line + "#define	DEFAULT_SUPPORT_OSD_LANGUAGE_Indonesian	 (UINT64)(0)//add by wanglong 2018 12.26"
					line_new.write(line)
					continue
				line_new.write(line)
			os.chdir(path1)
for parent,dirnames,filenames in os.walk('.'):			
	for dirname in dirnames:
		if os.path.isdir(dirname):	
			os.chdir(dirname)
			os.remove('config.h')                       #删除旧文件
			os.rename('config_new.h','config.h')        #修改文件名
			os.chdir(path1)
			

思路:在同一目录下,新建打开(w+模式)相同类型的文件用于保存文件内容。再逐行读取之前的文件,判断需要添加的位置,添加想添加的内容。最后删除旧文件,修改新文件名。

你可能感兴趣的:(Python,工作,其他)