python合并文本文件示例代碼。
python實現兩個文本合并
employee文件中記錄了工號和姓名
cat employee.txt:
100 Jason Smith 200 John Doe 300 Sanjay Gupta 400 Ashok Sharma
bonus文件中記錄工號和工資
cat bonus.txt:
100 $5,000 200 $500 300 $3,000 400 $1,250
要求把兩個文件合并并輸出如下, 處理結果:
400 ashok sharma $1,250 100 jason smith $5,000 200 john doe $500 300 sanjay gupta $3,000
這個應該是要求用shell來寫的,但我的shell功底不怎么樣,就用python來實現了
注意,按題目的意思,在輸出文件中還需要按照姓名首字母來排序的
#! /usr/bin/env python #coding=utf-8 fp01=open("bonus.txt","r") a=[] for line01 in fp01: a.append(line01) fp02=open("employee.txt","r") fc02=sorted(fp02,key=lambda x:x.split()[1]) for line02 in fc02: i=0 while line02.split()[0]!=a[i].split()[0]: i+=1 print "%s %s %s %s" % (line02.split()[0],line02.split()[1],line02.split()[2],a[i].split()[1]) fp01.close() fp02.close()
我們再來看一段同樣功能的 代碼
# coding gbk # # author: GreatGhoul # email : greatghoul@gmail.com # blog : http://greatghoul.javaeye.com import sys,os,msvcrt def join(in_filenames, out_filename): out_file = open(out_filename, 'w+') err_files = [] for file in in_filenames: try: in_file = open(file, 'r') out_file.write(in_file.read()) out_file.write('\n\n') in_file.close() except IOError: print 'error joining', file err_files.append(file) out_file.close() print 'joining completed. %d file(s) missed.' % len(err_files) print 'output file:', out_filename if len(err_files) > 0: print 'missed files:' print '--------------------------------' for file in err_files: print file print '--------------------------------' if __name__ == '__main__': print 'scanning...' in_filenames = [] file_count = 0 for file in os.listdir(sys.path[0]): if file.lower().endswith('[all].txt'): os.remove(file) elif file.lower().endswith('.txt'): in_filenames.append(file) file_count = file_count + 1 if len(in_filenames) > 0: print '--------------------------------' print '\n'.join(in_filenames) print '--------------------------------' print '%d part(s) in total.' % file_count book_name = raw_input('enter the book name: ') print 'joining...' join(in_filenames, book_name + '[ALL].TXT') else: print 'nothing found.' msvcrt.getch()
最后我們再來看一個小編遇到的情況:
今天匯編的時候在阿甘的博客里面看到了一部小說《瘋狂的程序員》,于是網上搜了下準備放到手機里閑時看看,無奈下載后發現是分章節的txt文本,一共有87個文件,考慮到閱讀起來不是很方便,于是想找個現成的工具合并txt文本。
結果嘗試了幾個工具后覺得合并效果都不給力啊,于是打算自己動手。其實cmd的命令"type *.txt >> crazy-programmer.txt"還是很有效果的,然而合并后的txt文件卻十分龐大,所以我還是自己寫了一個腳本完成了合并。
說明:由于我下載的87個txt文件的字符編碼格式都不統一,所以我用chardet模塊判斷字符編碼類型后再用codecs模塊的codecs.open功能解決了編碼問題。如果直接用file的open打開txt文件的話,在UCS-2 Little Endian的編碼情況下,file.read()遇到中文的冒號(即“:”)后會無法讀取冒號以后的內容,所以需要用codecs.open(path,'r',encoding)來解決。
如果還有問題可以留言,代碼如下:
#!coding: cp936 import codecs, chardet def fileopen(filename): f = open(filename, 'r') s = f.read() if(chardet.detect(s)['encoding'] == 'UTF-16LE'): f.close() f = codecs.open(filename, 'r', 'utf-16-le') data = f.read().encode('gb2312', 'ignore') f.close() elif(chardet.detect(s)['encoding'] == 'GB2312'): data = s f.close() return data i = 1 while i <=87: if(i < 10): filename = '0'+str(i)+'.txt' else: filename = str(i)+'.txt' text = fileopen(filename) file('crazy-p.txt', 'a+').write(text) i = i+1
其中,chardet模塊需要下載安裝,腳本還可以改進以適應更多種情況,我就懶了。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
