This paper introduces a method of dividing a large text file into several small files.
idea:
1. Read all the lines of the article and deposit it in the list
2. Defines the number of rows to be divided into small text
3. Write the contents of the original text to a small file by a certain number of lines
Code:
#coding: utf-8 #将大文本文件分割成多个小文本文件 import os sourcefilename = "test.txt" #定义要分割的文件 def cutfile (): Print U "Reading file ..." sourcefiledata = open (sourceFileName, ' r ') Listofline = Sourcefiledata.read (). Splitlines () #将 The contents of the read file are split by row and then saved in a list n = Len (listofline) Print U "file has a total of" +STR (n) +u "" Print U "Enter the number of files you want to split:" m = Int (raw_in Put (")) #定义分割的文件个数 p = n/m + 1 print u" need to divide the file into "+str (m) +u" sub file "Print U" each file has a maximum of "+str (p) +u" line "Print U" start to score
Cut it. For I in range (m): Print U "generating First" +str (i+1) +u "sub file" destFileName = Os.path.splitext (sourceFileName) [0]+] _pa RT "+str (i) +". txt "#定义分割后新生成的文件 destfiledata = open (destFileName," w ") if (i==m-1): For line in L Istofline[i*p:]: destfiledata.write (line+ ' \ n ') Else:for line in Listofline[i*p: (i+1) * P]: destfiledata.write (line+ ' \ n ') destfiledata.close () print U "split complete" cutfile ()
Run Result: