Python: Cut a large text file in small files containing user specified lines in each file

Dear Friends,

Very often you need to cut a large file in small files which contains equal number of lines. Consider the following scenerio:

I have a text files which contains 1000000 lines. I want to split it in files that contains 15000 lines each. E.g, first file contains 1 to 15000 lines, next file 15001 to 30000 lines and so on.

The following script will not only do so, but it will also create files with meaningful names.


lines = open('myfile.txt').readlines()
for i in range(0, 1000000, 15000):
   open('{0}_{1}.txt'.format(i+1, i+15000), 'w').writelines(lines[i:i+15000])
 
 
----------------------------------------------------------------------
 
Notes:
 
1. This will create files with names line 1_15000.txt which contain lines 1 to 15000,
15001_30000.txt which contain lines 15001 to 30000 and so on. 

Comments