#Python打開讀取一個文件內容,而後寫入一個新的文件中,並對某些字段進行提取,寫入新的字段的腳本。這是在工做中,需拼裝大量的8543報文,原報文只讀,不可寫入,且也要對原報文進行提取某字段、新增報文頭字段,刪除某字段等操做,但願你們有用的着的地方,與你們共同窗習進步!html
1 import os 2 import re 3 4 def get_filelist(dir): 5 os.getcwd() #get current work direction. 6 os.chdir(path) #change direction 7 Filelist = [] 8 for home, dirs, files in os.walk(path): 9 for filename in files: 10 #文件名列表,包含完整路徑 11 #Filelist1.append(os.path.join(home, filename)) 12 #文件名列表,只包含文件名 13 Filelist.append(filename) 14 return Filelist 15 16 def main(): 17 n=0 18 for file in filelist: 19 os.getcwd() #get current work direction. 20 os.chdir(path) #change direction 21 with open(file,mode='r',encoding='utf-8') as f1: 22 data=f1.read() 23 f1.close() 24 25 #切換到新的路徑下 26 os.getcwd() #get current work direction. 27 os.chdir(newpath) #change directio 28 29 #讀取文件的內容寫入到新file文件下 30 with open(file,mode='w',encoding='utf-8') as f2: 31 n=n+1 32 ##提取字段 拼裝寫入## 33 #系統簡稱大寫 34 SYST=file[file.find("")+0:file.find("")+4].upper() 35 #SYST=SYST.upper() 36 #print(SYST) 37 #發送行號 38 SEND1234SEND="660000000066" 39 #接收行號 40 RECV1234RECV="880000000088" 41 #刪除正則匹配的一行 42 data = re.sub(r'<!--.*-->\n', "", data) 43 #報文類型 44 MSGTYPE0MSGTYPE=data[data.find("tech:xsd:")+9:data.find("tech:xsd:")+24] 45 #MsgID 46 MSGRID0000MSGRID=data[data.find("<MsgId>")+7:data.find("<MsgId>")+23] 47 #拼裝的報文頭 48 head="{H:02"+SEND1234SEND+" "+SYST+RECV1234RECV+" "+SYST+"00000000000001XML"+MSGTYPE0MSGTYPE+" "+MSGRID0000MSGRID+" "+MSGRID0000MSGRID+" 3D }" 49 50 f2.write(head+'\n') 51 f2.write(data) 52 f2.close() 53 54 if os.path.isfile(file): 55 print(file,"轉換完成!") 56 else: 57 print(file,"轉換失敗!") 58 59 print("共轉換個文件數:",n) 60 61 62 if __name__ == '__main__': 63 path='E:\\辦公文檔\\LR項目資料\\XML格式報文示例' 64 newpath='E:\\Python_test\\讀取文件\\newfiles' 65 66 #path=input("請輸入文件路徑:") 67 #newpath=input("請輸入轉換後新文件路徑:") 68 69 filelist = get_filelist(dir) 70 #print(filelist) 71 #不用加引號,若是是多級目錄,只判斷最後一級目錄是否存在 72 if os.path.isdir(newpath): 73 #print ('dir exists') 74 pass 75 else: 76 #print ('dir not exists') 77 os.mkdir(newpath) 78 79 main() 80
可參考:shell讀取文件寫入新文件shell