By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,035 Members | 1,995 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,035 IT Pros & Developers. It's quick & easy.

Split a single file into multiple files

P: 21
I have file with 1000 lines. for example:
..
..
01-06 00:02:33.459 I/Activity( 32): Starting: {....APTPower}
..
..
..
..
01-06 00:02:34.563 I/Activity( 32): Starting: {....APTPower}
...
...
..
..
01-06 00:03:21.459 I/Activity( 32): Starting: {....APTPower}
..
..
I want to split file where ever Starting & APTPower occurs and writing it to new file until next occurance of pattern i.e., starting & APTPower.

How do i do that?
Aug 9 '11 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
First you should decide on how to name the files you are writing to. I would suggest a starting name and increment the name from there. Something like:
Expand|Select|Wrap|Line Numbers
  1. >>> for i in range(10):
  2. ...     fn = "filename%s" % (i)
  3. ...     print fn
  4. ...     
  5. filename0
  6. filename1
  7. filename2
  8. filename3
  9. filename4
  10. filename5
  11. filename6
  12. filename7
  13. filename8
  14. filename9
  15. >>> 
Iterate on the open file object and test each line for membership of keywords. When both keywords are in the line, close the open file object for writing and open a new one.
Expand|Select|Wrap|Line Numbers
  1. fread = open("data11.txt")
  2. count = 1
  3. fwrite = open("filename%s" % (count), 'w')
  4. for line in fread:
  5.     if "Starting" in line and "APTPower" in line:
  6.         # close open file object, increment count, open new file object
  7.         fwrite.close()
  8.         count += 1
  9.         fwrite = open("filename%s" % (count), 'w')
  10.         fwrite.write(line + "\n")
  11.     else:
  12.         fwrite.write(line + "\n")
  13. fwrite.close()
  14. fread.close()
Aug 9 '11 #2

P: 21
thanks you, it was helpful....
Aug 9 '11 #3

Post your reply

Sign in to post your reply or Sign up for a free account.