Reading binary files
davea at ieee.org
Mon Aug 24 20:35:21 CEST 2009
Ronn Ross wrote:
> On Mon, Aug 24, 2009 at 11:18 AM, Ronn Ross <ronn.ross at gmail.com> wrote:
>> On Mon, Aug 24, 2009 at 10:43 AM, Albert Hopkins <marduk at letterboxes.org>wrote:
>>> On Mon, 2009-08-24 at 10:35 -0400, Ronn Ross wrote:
>>>> I need to read a binary file. When I open it up in a text editor it is
>>>> just junk. Does Python have a class to help with this?
>>> Yes, the "file" class.
>>>>>> myfile = open('/path/to/binary/file', 'rb')
>> This works for a simple binary file, but the actual file I'm trying to read
>> is give throwing an error that the file cannot be found. Here is the name of
>> the my file:
>> Should python have trouble reading this file name or extension?
> I'm having trouble with the filename:
> It throws an error with that file name, When I change it to something like
> sample.txt it runs, but the data is still garbled. Is there any reason why I
> can't use the above file name? If I'm using 'rb' to read the binary file why
> is it still garbled?
You're describing two separate problems here. One is an error in the
open statement, and the other is "something is garbled."
If you hand a relative path name to the open() function, it'll have to
get the absolute path from somewhere else, presumably the current
directory. Do you know for sure what the current directory is, and is
that file located there? Try printing os.path.abspath(os.curdir). Or
pass a complete (absolute) path to open().
As for garbled... Just what do you expect? A binary file is a
completely arbitrary sequence of bytes. So if you're trying to print
it, you may see "garbled." Just what is the file's purpose anyway? You
can't do much with it without knowing something about it.
More information about the Python-list