#-*-coding:utf-8-*-#__author__:'Administrator'#@Time:2018/8/3114:19importosdst="D:\\test"#生成文件目录#放一个txt的内容file,按照哪些章节拆分defSplitFile(file_path1,dst):withopen(file_path1,'rb')asf1:#获取文件的每一行lines1=f1.readlines()#获取文件名file_dir1=file_path1.replace("\\",'/').split("/")[-1].split(".")[0]path1=os.path.join(dst,file_dir1)如果不是os.path.exists(path1):os.makedirs(path1)i=1forlineinlines1:try:if("section"inlineand"chapter"inline)or("section"inlineand"chapter..."inline)or("第"inlineand"Chapter\r\n"inline):name=line.strip().decode('utf8')i+=1else:fp=open(file_name1,'ab+')fp.write(line)fp.close()file_name1=os.path.join(path1,"%s_%s.txt"%(i-1,name))exceptExceptionase:printe.message#将一个txt文件的内容,按照数字顺序进行分割defSplitFile_by_Num(file_path2,dst):以open(file_path2,'rb')作为f2:lines2=f2.readlines()file_dir2=file_path2.replace("\\",'/').split("/")[-1].split(".")[0]path2=os.path.join(dst,file_dir2)如果不是os.path.exists(path2):os.makedirs(path2)i=1forlineinlines2:try:if("%s\r\n"%i)inlineor("%s、"%iinline)or("%s"%iinline)orstr(i)inline:name=line.strip().decode('utf8')i+=1else:fp=open(file_name2,'ab+')fp.write(line)fp.close()file_name2=os.path.join(path2,"%s_%s.txt"%(i-1,name))exceptExceptionase:printe.message#获取某个目录下面的所有txtdefget_all_txt(path):filepaths=[]forroot,dirs,filesinos.walk(path):fornameinfiles:if'.txt'inname:filepaths.append(os.path.join(root,name))returnfilepathsif__name__=="__main__":file_dir="D:\\xiaoshuo"file_paths=get_all_txt(unicode(file_dir,"utf8"))foroneinfile_paths:SplitFile(one,dst)forroot,dirs,filesinos.walk(os.path.join(dst,one.replace("\\",'/').split("/")[-1].split(".")[0])):如果不是文件:SplitFile_by_Num(one,dst)
