Binary File Parsing and Creation of new Files

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • drd0s
    New Member
    • Nov 2012
    • 2

    Binary File Parsing and Creation of new Files

    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 :

    Code:
    #!/usr/bin/python
    
    with open("file", "rb") as f:
    	byte = f.read()
    	if byte > 820:
    	    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 .
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    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:
    Code:
    import io
    f = io.FileIO(file_name)
    while True:
        s = f.read(10)
        if not s:
            break
        print "******"
        print s
        print s[2:7]
        print "******"
    f.close()

    Comment

    • drd0s
      New Member
      • Nov 2012
      • 2

      #3
      nice i made after this my way that was like this :
      Code:
      n = 820
      with open('/home/drdos/work/file.PDA', "rb") as f:
          while True:
              data = f.read(n)
              if not data:
                  break
              
              filename = str(data[16:32])
              
              x = open(filename, 'wb').write(data)
      Last edited by bvdet; Nov 30 '12, 06:17 PM. Reason: Please use code tags when posting code [code].....[/code]

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        One thing you left off:
        Code:
                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.

        Comment

        Working...