how to read all bytes of a file in a list?

Peter Hansen peter at engcorp.com
Mon Dec 16 14:34:26 EST 2002


Benjamin wrote:
> 
> i have a file, and wrote a little program which should load every
> single byte of the file into a list.
> 
> file_location = raw_input("file path > ")
> 
> list = []
> 
> input = open(file_location,"r")
> s = input.read()
> s = str(s)
> print s
> input.close()
> 
> print list

Given that you never store anything in the "list", it's no wonder
this doesn't do what you expect.  Here are a few pointers:

1. Try to avoid using keywords or builtin names as variable names.
   List is one such to avoid.  Use 'lst' or 'l' or 'x' or 'charlie'
   or something, but not "list".

2. The real answer depends on what you really want to do.  Lists in
   Python are one type of "sequence".  So are strings.  The code
   above reads all the bytes into a string called "s" (which, by
   the way, is already a string, so doing "s = str(s)" is completely
   redundant.  You would generally work with the data in this 
   form, not in a list.  You might want to put each *line* in the
   file into a list, in which case use .readlines() instead of .read().

3. "input" is also a builtin name, but since you probably 
   shouldn't be using it (use raw_input instead) it's probably not a
   bad idea to hide it by reusing the name. ;-)

4. If you *really* want each byte listed separately in an actual  
   Python list object, use "s = list(s)" after the read() and your
   bytes will be in a list called "s".  I don't recommend this at
   all, either for performance or ease of manipulation, although 
   it will work fine if you're just tooling around.

-Peter



More information about the Python-list mailing list