关键词:python 文件操作 读取文件
python实现文件操作(读取、切割、查找、归并)
import codecs def readfile(filepath):#文件读取 file = codecs.open(filepath, "r") biglist = file.read() print(type(biglist)) for list in biglist: print(biglist) file.close() ##################################################################################################### def qgfile(filepath):#文件切割 fileopen=open(filepath, "rb") num=10 filelist=[] for i in range(num): savepath="E:\\学习\\Python\\学习资料\\零散\\YinchengDay5\\data\\"+"data"+str(i+1)+".txt" filesave=open(savepath,"wb") filelist.append(filesave) print(filelist) i = 0 for line in fileopen: filelist[i % num].write(line) i += 1 fileopen.close() for i in range(num): filelist[i].close() # 关闭文件 ####################################################################################################### def findfile():#文件查找 #读取文件 print("查找开始。。。") filepath="E:\\学习\\Python\\学习资料\\零散\\YinchengDay5\\data\\1.txt" file=open(filepath,"r") filestr=file.readlines() #存入文件 file163path = "E:\\学习\\Python\\学习资料\\零散\\YinchengDay5\\data\\163.com.txt" filenot163path="E:\\学习\\Python\\学习资料\\零散\\YinchengDay5\\data\\其它邮箱.txt" filesave = open(file163path, "w") filesave_QT=open(filenot163path,"w") i = 0 while i < len(filestr): if filestr[i].find("163.com") > -1: filesave.write(filestr[i]) i += 1 else: filesave_QT.write(filestr[i]) i += 1 filesave.close() file.close() print("查找结束。。。") ####################################################################################################### def merge(mylist1,mylist2): # 文件归并 mylistall=[] i1=0 i2=0 while i1< len(mylist1) and i2 <len(mylist2)>0: #有一个结束,没有必须要对比 if mylist1[i1] <mylist2[i2]: #谁大选谁 mylistall.append(mylist1[i1]) i1+=1 #下标移动 elif mylist1[i1] >mylist2[i2]: mylistall.append(mylist2[i2]) i2+=1 #下标移动 else: mylistall.append(mylist2[i2]) i1+=1 i2+=1 while i1<len(mylist1): #粘贴尾部 mylistall.append(mylist1[i1]) i1+=1 while i2 < len(mylist2): mylistall.append(mylist2[i2]) i2 += 1 return mylistall bigfilepath=r"E:\学习\Python\学习资料\零散\YinchengDay5\mail.txt" #readfile(bigfilepath) #qgfile(bigfilepath) findfile()