python分批定量讀取文件內(nèi)容,輸出到不同文件中的方法
一、文件內(nèi)容的分發(fā)
應(yīng)用場(chǎng)景:分批讀取共有358086行內(nèi)容的txt文件,每取1000條輸出到一個(gè)文件當(dāng)中
# coding=utf-8
# 分批讀取共有358086行內(nèi)容的txt文件,每取1000條輸出到一個(gè)文件當(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)用場(chǎng)景:分批讀取目錄下的文件,每取1000條輸出到一個(gè)新的目錄當(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)容,輸出到不同文件中的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Keras 切換后端方式(Theano和TensorFlow)
這篇文章主要介紹了Keras 切換后端方式(Theano和TensorFlow),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
flask 框架操作MySQL數(shù)據(jù)庫(kù)簡(jiǎn)單示例
這篇文章主要介紹了flask 框架操作MySQL數(shù)據(jù)庫(kù),結(jié)合實(shí)例形式詳細(xì)分析了flask框架操作MySQL數(shù)據(jù)庫(kù)的連接、表格創(chuàng)建、數(shù)據(jù)增刪改查等相關(guān)使用技巧,需要的朋友可以參考下2020-02-02
python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的小工具
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的小工具,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09
python密碼學(xué)簡(jiǎn)單替代密碼解密及測(cè)試教程
這篇文章主要介紹了python密碼學(xué)簡(jiǎn)單替代密碼解密及測(cè)試教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
使用C語(yǔ)言擴(kuò)展Python程序的簡(jiǎn)單入門(mén)指引
這篇文章主要介紹了使用C語(yǔ)言擴(kuò)展Python程序的簡(jiǎn)單入門(mén)指引,來(lái)自于IBM官網(wǎng)網(wǎng)站技術(shù)文檔,需要的朋友可以參考下2015-04-04
Python?Struct庫(kù)之pack和unpack舉例詳解
這篇文章主要給大家介紹了關(guān)于Python?Struct庫(kù)之pack和unpack的相關(guān)資料,pack和unpack在處理二進(jìn)制流中比較常用的封包、解包格式,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-02-02

