替换文本内容
一个简单的例子,查看当前文件路径中的文件,查找有‘bye’字符的行,并修改为‘bye’。
注: else:
file_out.write(line)
这两行代码不能少,保证了没有包含‘bye’字符的行也可以被重新写入文件中,防止了处理完成后文件中只剩下字符所在行。
#!/usr/bin/python import os def chtext(filename): file_handle = open(filename,'r') lines = file_handle.readlines() file_handle.close() file_out = open(filename,'w') for line in lines: if not line: break if 'bye' in line: file_out.write(line.replace('bye','bye')) else: file_out.write(line) file_out.close() def chkname(): path=os.path.abspath(".") print("path is %s" %(path)) filelist = os.listdir(path) for root,dirname,filename in os.walk(path): for f in filename: print("name is: %s" %f) chtext(os.path.join(root,f)) # object_handle = open(files) # file_text = object_handle.read() # print(" %s" %(file_text)) # object_handle.close() chkname()