- 工信部備案號 滇ICP備05000110號-1
- 滇公網(wǎng)安備53011102001527號
- 增值電信業(yè)務經(jīng)營許可證 B1.B2-20181647、滇B1.B2-20190004
- 云南互聯(lián)網(wǎng)協(xié)會理事單位
- 安全聯(lián)盟認證網(wǎng)站身份V標記
- 域名注冊服務機構(gòu)許可:滇D3-20230001
- 代理域名注冊服務機構(gòu):新網(wǎng)數(shù)碼
python合并文本文件示例代碼。
python實現(xiàn)兩個文本合并
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
要求把兩個文件合并并輸出如下, 處理結(jié)果:
400 ashok sharma $1,250 100 jason smith $5,000 200 john doe $500 300 sanjay gupta $3,000
這個應該是要求用shell來寫的,但我的shell功底不怎么樣,就用python來實現(xiàn)了
注意,按題目的意思,在輸出文件中還需要按照姓名首字母來排序的
#! /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://lncdfzh.com.cn
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()最后我們再來看一個小編遇到的情況:
今天匯編的時候在阿甘的博客里面看到了一部小說《瘋狂的程序員》,于是網(wǎng)上搜了下準備放到手機里閑時看看,無奈下載后發(fā)現(xiàn)是分章節(jié)的txt文本,一共有87個文件,考慮到閱讀起來不是很方便,于是想找個現(xiàn)成的工具合并txt文本。
結(jié)果嘗試了幾個工具后覺得合并效果都不給力啊,于是打算自己動手。其實cmd的命令"type *.txt >> crazy-programmer.txt"還是很有效果的,然而合并后的txt文件卻十分龐大,所以我還是自己寫了一個腳本完成了合并。
說明:由于我下載的87個txt文件的字符編碼格式都不統(tǒng)一,所以我用chardet模塊判斷字符編碼類型后再用codecs模塊的codecs.open功能解決了編碼問題。如果直接用file的open打開txt文件的話,在UCS-2
Little
Endian的編碼情況下,file.read()遇到中文的冒號(即“:”)后會無法讀取冒號以后的內(nèi)容,所以需要用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模塊需要下載安裝,腳本還可以改進以適應更多種情況。
售前咨詢
售后咨詢
備案咨詢
二維碼

TOP