欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python处理文本文件并生成指定格式的文件

程序员文章站 2024-02-01 21:03:40
import os import sys import string #以指定模式打开指定文件,获取文件句柄 def getfileins(f...
import os 
import sys 
import string 
 
#以指定模式打开指定文件,获取文件句柄 
def getfileins(filepath,model): 
  print("打开文件") 
  print(filepath) 
  print(model) 
  return open(filepath,model) 
 
#获取需要处理的文件 
def getprocfile(path): 
  return os.listdir(path) 
 
#判断是否满足某个条件,如果满足则执行 
def istrue(outfileins,s): 
  findstr1 = "line_count_update   integer := 0;" 
  writestr1 = "line_count_error    integer := 0;    --错误数据xx条" 
  findstr2 = "dbms_output.put_line('处理完毕" 
  writestr2 = "dbms_output.put_line('错误数据['||line_count_error||']条.');" 
  findstr3 = "dbms_output.put_line('插入数据['||cur_result.int_id||']时发生异常...');" 
  writestr3 = "line_count_error := line_count_error+1;" 
  findstr4 = "dbms_output.put_line('更新数据['||cur_result.int_id||']时发生异常...');" 
   
  if s.find(findstr1) != -1: 
    outfileins.write(s) 
    outfileins.write(writestr1+"\n") 
  elif s.find(findstr2) != -1: 
    outfileins.write(s) 
    outfileins.write(writestr2+"\n") 
  elif s.find(findstr3) != -1: 
    outfileins.write(s) 
    outfileins.write("\t\t\t\t"+writestr3+"\n") 
  elif s.find(findstr4) != -1: 
    outfileins.write(s) 
    outfileins.write("\t\t\t\t\t"+writestr3+"\n") 
  elif s.find("cs_oslgis") != -1: 
    outfileins.write(s.replace("cs_oslgis","cq_rmw")) 
  elif s.find("and a.longitude >") != -1: 
    outfileins.write("\t\t\tand a.longitude is not null\n\t\t\tand a.longitude is not null\n\t\t\tand rownum<2\n") 
  elif s.find(") loop") != -1: 
    outfileins.write("\t\t) loop\n") 
  else: 
    outfileins.write(s.replace("||')',2","||')',3")) 
 
#读取并处理文本 
def getandproc(infileins,outfileins): 
  lines = infileins.readlines() 
  for s in lines: 
    #print(s) 
    istrue(outfileins,s) 
 
if __name__=="__main__": 
   
  infilemod = "r" 
  outfilemod = "w" 
  path = "d:\\rmsdata2gis" 
  for tmpfile in os.listdir(path): 
    infilepath = path+"\\"+tmpfile 
    outfilepath = path+"\\bak_"+tmpfile 
    infileins = getfileins(infilepath,infilemod) 
    outfileins = getfileins(outfilepath,outfilemod) 
    getandproc(infileins,outfileins) 
    infileins.close() 
    outfileins.close()