分割文本文件

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

import os

file = "book1.txt"  # 文件名称
txt = ""
try:
    f = open(file, "r")
    while True:
        l = f.readline()
        if l:
            txt += l
        else:
            break    
except:
    f.close()
    f = open(file, "r", encoding="utf-8")
    while True:
        l = f.readline()
        if l:
            txt += l
        else:
            break       

f.close()

i_count = 10000     # 按指定字数分割
i_page = int(len(txt) / i_count) + 1
for i in range(i_page):
    i_begin = i * i_count
    i_end = (i + 1) * i_count
    if i == i_page - 1:
        i_end = len(txt)
    s1 = txt[i_begin : i_end]
    
    s_dir = file.replace(".txt", "")
    if not os.path.exists(s_dir):
        os.makedirs(s_dir)
    
    file_c = s_dir + "/" + s_dir + "_" + str(i + 1) + ".txt"
    try:
        f = open(file_c, "w")
        f.write(s1)
    except:
        f.close()
        f = open(file_c, "w", encoding="utf-8")
        f.write(s1)        
    f.close()

print("finished!")