将大文本文件分割成多个小文件

本文介绍一种将一个大的文本文件分割成多个小文件的方法

思路:
1.读取文章所有的行,并存入列表中
2.定义分割成的小文本的行数
3.将原文本内容按一定行数依次写入小文件中

代码:

#coding:utf-8
#将大文本文件分割成多个小文本文件
import os

sourceFileName = "test.txt" #定义要分割的文件
def cutFile():
    print u"正在读取文件..."
    sourceFileData = open(sourceFileName,'r')
    ListOfLine = sourceFileData.read().splitlines()#将读取的文件内容按行分割,然后存到一个列表中
    n = len(ListOfLine)
    print u"文件共有"+str(n)+u"行"
    print u"请输入需要将文件分割的个数:"
    m = int(raw_input("")) #定义分割的文件个数
    p = n/m + 1
    print u"需要将文件分成"+str(m)+u"个子文件"
    print u"每个文件最多有"+str(p)+u"行"
    print u"开始进行分割···"
    for i in range(m):
        print u"正在生成第"+str(i+1)+u"个子文件"
        destFileName = os.path.splitext(sourceFileName)[0]+"_part"+str(i)+".txt" #定义分割后新生成的文件
        destFileData = open(destFileName,"w")
        if(i==m-1):
            for line in ListOfLine[i*p:]:
                destFileData.write(line+'\n')
        else:
            for line in ListOfLine[i*p:(i+1)*p]:
                destFileData.write(line+'\n')
        destFileData.close()
    print u"分割完成"

cutFile()

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/d1240673769/article/details/77513091
今日推荐