Python實現大文字檔案分割

2021-09-16 19:37:14 字數 3225 閱讀 6443

python 2

通過檔案拖拽或檔案路徑輸入,實現自定義大文字檔案分割。

#coding:gbk

import os,sys,shutil

is_file_exits=

false

while

not is_file_exits:

files_list=

if(len(sys.ar**)==1

):print

('請輸入要切割的檔案完整路徑:'

) files_path=

raw_input()

.strip(

)for str_file_path in files_path.split(

' '):if

(str_file_path.strip()==

''):continueif(

not os.path.exists(str_file_path.strip())

):print

(str_file_path.strip()+

'檔案路徑不存在,請重新輸入!'

) is_file_exits=

false

break

else:)

);is_file_exits=

true

else

:for str_file_path in sys.ar**[1:

len(sys.ar**)]:

if(str_file_path.strip()==

''):continueif(

not os.path.exists(str_file_path.strip())

):print

(str_file_path.strip()+

'檔案路徑不存在,請重新輸入!'

) is_file_exits=

false

break

else:)

);is_file_exits=

true

print

('待切割檔案:'

+str

(files_list)

)

is_continue=

false

while

not is_continue:

print

('請輸入要切割的檔案個數:'

) str_files_count=

raw_input()

if str_files_count.isdigit():

is_continue=

true

else

:print

('請輸入正確的數字!'

)for file_path in files_list:

split_file_path=

'' total_lines_count=

0 lines_count=

0 files_count=

int(str_files_count)

print

('正在統計文字行數.....'

)

total_lines_count =

len(

open

(file_path,

'ru'

).readlines())

print

('文字總行數:'

+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_numfile_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+=

1print

(file_path+

'分割完成!'

)

split_file.close(

)

os.system(

'pause'

)

linux下分割文字檔案

linux split 命令 功能說明 切割檔案。語 法 split help version 行數 b 位元組 c 位元組 l 行數 要切割的檔案 輸出檔名 補充說明 split可將檔案切成較小的檔案,預設每1000行會切成乙個小檔案。參 數 行數 或 l 行數 指定每多少行就要切成乙個小檔案。b...

shell按行分割文字檔案

大家常用的分割文字的方法都是通過sed n 命令來操作,sed 的優點是可以指定具體的行,缺點每次分割要重新讀取整個文字,效率低了點。在高人指點下發現split這個方法好用些,也參考了其他的資料總結一下split用法。split 引數 需要分割的檔案 b size 對file進行切分,每個小檔案大小...

用Python實現大文字檔案切割的方法

在實際工作中,www.cppcns.com有些場景下,因為產品既有功能限制,不支援特大檔案的直接處理,需要把大檔案進行切割處理。而且,對程式設計師來說,diy乙個輪子還是有必要的。python作為快速開發工具,其 表達力強,開發效率高,因此用python快速寫乙個,還是可行的。需求描述 輸入 給定乙...