bhishan

split_whole_file_in_nparts_with_comments

Jun 22nd, 2016
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Author    : Bhishan Poudel
  4. # Date      : Jun 22, 2016
  5.  
  6.  
  7. # Imports
  8. from __future__ import print_function
  9. import numpy as np
  10. import pandas as pd
  11. import matplotlib.pyplot as plt
  12.  
  13.  
  14. infile = r'input.txt'
  15.  
  16. with open(infile, 'r') as f:
  17.     data = f.readlines()
  18.  
  19. ##=============================================================================
  20. # get number of comments line
  21. comments_lines = 0
  22. for line in data:
  23.     if line.strip().startswith('#'):
  24.         comments_lines += 1
  25.     else:
  26.         break
  27.  
  28. print('{} {} {}'.format('comment_lines = ',comments_lines, '\n\n'))
  29.  
  30.  
  31.  
  32.  
  33. ##=============================================================================
  34. nfiles = 20
  35. chunk_size = (len(data)-comments_lines)//nfiles
  36.  
  37. for i in range(nfiles):
  38.     with open('temp/output_{:02d}.txt'.format(i), 'w') as f:
  39.  
  40.         # add equal chunk_size data to all files
  41.         lower = comments_lines + i      * chunk_size
  42.         upper = comments_lines + (i+1 ) * chunk_size
  43.        
  44.         f.write( ''.join (  data[:comments_lines] +  data  [lower :  upper ] ))
  45.  
  46.         # description
  47.         print('{} {} {}'.format('lower = ',lower, ''))
  48.         print('{} {} {}'.format('uppper = ',upper, ''))
  49.  
  50.         # add more lines to last file, if exist
  51.         if (i == nfiles - 1) and (len(data) > upper):
  52.             f.write(''.join(data[upper:]))
  53.  
  54.             # description
  55.             print('{} {} {}'.format('\ni = ',i, ''))
  56.             print('{} {} {}'.format('len data = ',len(data), ''))            
  57.             print('{} {} {}'.format('comment_lines = ',comments_lines, ''))
Advertisement
Add Comment
Please, Sign In to add comment