python分批定量讀取文件內(nèi)容,輸出到不同文件中的方法
一、文件內(nèi)容的分發(fā)
應(yīng)用場景:分批讀取共有358086行內(nèi)容的txt文件,每取1000條輸出到一個文件當(dāng)中
# coding=utf-8 # 分批讀取共有358086行內(nèi)容的txt文件,每取1000條輸出到一個文件當(dāng)中 txt_path = "E:/torrenthandle.txt" base_path="E:/torrent_distribution/" def distribution( ): f = open(txt_path,"r") lines = f.readlines() f2=open(base_path+"1.txt","w") content="" for i in range( 1,len(lines) ): if ( i%1000!=0 ): content+=lines[i-1] else: content+=lines[i-1] f2.write(content.strip('\n')) block_path=base_path+str(i)+".txt" f2=open(block_path,"w") content="" #最后的掃尾工作 content+=lines[i] f2.write(content.strip('\n')) f2.close() f.close() distribution( )
二、文件夾(目錄)下的內(nèi)容分發(fā)
應(yīng)用場景:分批讀取目錄下的文件,每取1000條輸出到一個新的目錄當(dāng)中
# coding: utf-8 import os import shutil sourcepath = "E:\\sample" distribution_path = "E:\\sample\\distribution\\" if __name__ =='__main__': rs = unicode(sourcepath , "utf8") count = 1 savepath = unicode(distribution_path+"1", "utf-8") if not os.path.exists(savepath): os.makedirs(savepath) for rt,dirs,files in os.walk(rs): for fname in files: if ( count%1000!=0 ): shutil.copy(rt + os.sep + fname,savepath) #os.remove(rt + os.sep + fname) else: shutil.copy(rt + os.sep + fname,savepath) #os.remove(rt + os.sep + fname) savepath = unicode(distribution_path+str(count), "utf-8") if not os.path.exists(savepath): os.makedirs(savepath) count+=1
以上這篇python分批定量讀取文件內(nèi)容,輸出到不同文件中的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Keras 切換后端方式(Theano和TensorFlow)
這篇文章主要介紹了Keras 切換后端方式(Theano和TensorFlow),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06flask 框架操作MySQL數(shù)據(jù)庫簡單示例
這篇文章主要介紹了flask 框架操作MySQL數(shù)據(jù)庫,結(jié)合實例形式詳細(xì)分析了flask框架操作MySQL數(shù)據(jù)庫的連接、表格創(chuàng)建、數(shù)據(jù)增刪改查等相關(guān)使用技巧,需要的朋友可以參考下2020-02-02python實現(xiàn)統(tǒng)計代碼行數(shù)的小工具
這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)統(tǒng)計代碼行數(shù)的小工具,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-09-09Python?Struct庫之pack和unpack舉例詳解
這篇文章主要給大家介紹了關(guān)于Python?Struct庫之pack和unpack的相關(guān)資料,pack和unpack在處理二進制流中比較常用的封包、解包格式,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-02-02