5

I want to copy a file without the first 256 bytes.

Is there a nice way to do it in python?

I guessing that the simple way is to read byte-byte with a counter and then start copy only when it get to 256.

I was hoping for more elegant way.

Thanks.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
ZoRo
  • 401
  • 2
  • 5
  • 12
  • 1
    It makes more sense if you read file to the end and then just write whatever you want to another file. – Mehraban Aug 27 '13 at 12:47
  • 1
    `f.seek(255)` might work. [Docs](http://docs.python.org/2/tutorial/inputoutput.html) – keyser Aug 27 '13 at 12:49
  • Ignore the answers telling you to seek. Unless `file` == `regular file`, seeking will fail. If `file` == `regular file` in one's mind, then one has failed to grok the beauty of unix. – William Pursell Aug 27 '13 at 13:34
  • Hi @WilliamPursell , I just read [here](http://docs.python.org/2/tutorial/inputoutput.html) and [there](http://www.tutorialspoint.com/python/file_seek.htm). Didn't saw any warning about file.seek. Can you explain your comment? – ZoRo Aug 28 '13 at 04:14
  • 2
    `fseek` will fail on pipes, sockets, and many other files. It is only useful with regular files. The unix philosophy advocates for programs that can work as filters (using pipes instead of regular files), because a tool is more useful/flexible if it is able to work on non regular files as well as regular files. Using seek needlessly restricts the utility of your tool. – William Pursell Aug 28 '13 at 14:45

3 Answers3

8
with open('input', 'rb') as in_file:
    with open('output', 'wb') as out_file:
        out_file.write(in_file.read()[256:])
FogleBird
  • 74,300
  • 25
  • 125
  • 131
7

Use seek to skip the first 256 bytes, then copy the file in chunks to avoid reading the entire input file into memory. Also, make sure to use with so that the file is closed properly:

with open('input.dat', 'rb') as inFile:
    inFile.seek(256)
    with open('output.dat', 'wb') as outFile:
        for chunk in iter(lambda: inFile.read(16384), ''):
            outFile.write(chunk)
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
4
f = open('filename.ext', 'rb')
f.seek(255) # skip the first 255 bytes
rest = f.read() # read rest
bpgergo
  • 15,669
  • 5
  • 44
  • 68