Split large text files into smaller files

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.