python實現(xiàn)大文本文件分割
更新時間:2019年07月22日 10:15:51 作者:Angryshark_128
這篇文章主要為大家詳細介紹了python實現(xiàn)大文本文件分割,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了python實現(xiàn)大文本文件分割的具體代碼,供大家參考,具體內(nèi)容如下
開發(fā)環(huán)境
Python 2
實現(xiàn)效果
通過文件拖拽或文件路徑輸入,實現(xiàn)自定義大文本文件分割。
代碼實現(xiàn)
#coding:gbk import os,sys,shutil is_file_exits=False while not is_file_exits: files_list=[] if(len(sys.argv)==1): print('請輸入要切割的文件完整路徑:') files_path=raw_input().strip() for str_file_path in files_path.split(' '): if(str_file_path.strip()==''): continue if(not os.path.exists(str_file_path.strip())): print(str_file_path.strip()+'文件路徑不存在,請重新輸入!') is_file_exits=False break else: files_list.append(str_file_path.strip()); is_file_exits=True else: for str_file_path in sys.argv[1:len(sys.argv)]: if(str_file_path.strip()==''): continue if(not os.path.exists(str_file_path.strip())): print(str_file_path.strip()+'文件路徑不存在,請重新輸入!') is_file_exits=False break else: files_list.append(str_file_path.strip()); is_file_exits=True print('待切割文件:'+str(files_list)) is_continue=False while not is_continue: print('請輸入要切割的文件個數(shù):') str_files_count=raw_input() if str_files_count.isdigit(): is_continue=True else: print('請輸入正確的數(shù)字!') for file_path in files_list: split_file_path='' total_lines_count=0 lines_count=0 files_count=int(str_files_count) print('正在統(tǒng)計文本行數(shù).....') total_lines_count = len(open(file_path,'rU').readlines()) print('文本總行數(shù):'+str(total_lines_count)) if files_count>total_lines_count: print('文本太小,不值得分割!') sys.exit() (filepath,filename) = os.path.split(file_path); (filepathname,extension) = os.path.splitext(file_path) if os.path.exists(filepathname): shutil.rmtree(filepathname) os.mkdir(filepathname) lines_count=int(total_lines_count/files_count) mod_count=total_lines_count%files_count print('正在進行文件分割.....') line_num=0 file_num=0 temp=-1 for line in open(file_path,'rU').readlines(): if file_num<mod_count: file_num=int(line_num/(lines_count+1)) else: file_num=int((line_num-mod_count*(lines_count+1))/lines_count+mod_count) split_file_path=filepathname+'/'+str.replace(filename,extension,'_'+str(file_num)+extension) with open(split_file_path,'a+') as split_file: split_file.write(line) if temp!=file_num: print('正在生成:'+split_file_path) temp=file_num line_num+=1 print(file_path+'分割完成!') split_file.close() os.system('pause')
源碼地址
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
代碼講解Python對Windows服務(wù)進行監(jiān)控
本篇文章給大家分享了通過Python對Windows服務(wù)進行監(jiān)控的實例代碼,對此有興趣的朋友可以學(xué)習(xí)參考下。2018-02-02Python讀取Excel數(shù)據(jù)并生成圖表過程解析
這篇文章主要介紹了Python讀取Excel數(shù)據(jù)并生成圖表過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06深入探討PythonLogging模塊的高級用法與性能優(yōu)化
在Python應(yīng)用程序中,日志處理是一項至關(guān)重要的任務(wù),本文將探索Logging模塊的高級用法,包括日志級別、格式化、處理程序等方面的功能,需要的可以參考下2024-04-04