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

Fredrik Lundh fredrik at pythonware.com
Mon Dec 16 14:38:10 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
>
> well, i just don't get it. i tried also some other versions, but none
> worked. what am i doing wrong?

the problem is a bit underspecified: what do you want
to put in the list?

the entire file, as a single string?

    input = file(file_location, "r")
    L = [input.read()]
    print L

each character in the text file?

    input = file(file_location, "r")
    L = list(input.read())

each byte in a binary file?

    input = file(file_location, "rb")
    L = list(input.read())

each line in a text file?

    input = file(file_location, "r")
    L = input.readlines()

(etc)

</F>





More information about the Python-list mailing list