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

Binary File Parsing and Creation of new Files

P: 2
I have a file ( size : 20 mb | binary file ) that needs to be parsed every 820 bytes and that very content of 820 saved into a new file with the name of the file being the string(ASCII) between the 2byte and the 16byte mark.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
^ THE FILENAME COMES FROM HERE ^

Ok now that the challenge is explained ( i hope ) what i do have for now is this :

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2.  
  3. with open("file", "rb") as f:
  4.     byte = f.read()
  5.     if byte > 820:
  6.         print "Reach the 1 record mark on the File you have defined "

Hmmm i don't know how to iterate every time i read the buffer and the f.read reaches 820 bytes and save it to a new file every 820bytes then the next 820bytes and continue to the end of the file .
Nov 30 '12 #1
Share this Question
Share on Google+
3 Replies

bvdet
Expert Mod 2.5K+
P: 2,851
The io module is suitable for reading raw bytes. Read 840 bytes and save to an identifier. Write the 840 bytes out using a slice of the saved string (s[2:17] in your case) as the file name. Here's a simple example of using io.FileIO:
Expand|Select|Wrap|Line Numbers
  1. import io
  2. f = io.FileIO(file_name)
  3. while True:
  4.     s = f.read(10)
  5.     if not s:
  6.         break
  7.     print "******"
  8.     print s
  9.     print s[2:7]
  10.     print "******"
  11. f.close()
Nov 30 '12 #2

P: 2
nice i made after this my way that was like this :
Expand|Select|Wrap|Line Numbers
  1. n = 820
  2. with open('/home/drdos/work/file.PDA', "rb") as f:
  3.     while True:
  4.         data = f.read(n)
  5.         if not data:
  6.             break
  7.  
  8.         filename = str(data[16:32])
  9.  
  10.         x = open(filename, 'wb').write(data)
Nov 30 '12 #3

bvdet
Expert Mod 2.5K+
P: 2,851
One thing you left off:
Expand|Select|Wrap|Line Numbers
  1.         x.close()
That ensures the data will be flushed to disk and you are not left with an open file.

Maybe you should use a try/except block in case filename has characters unsuitable for a file name.
Nov 30 '12 #4

Post your reply

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