Python Reading From and Writing to Binary Files

Viewed 3246

The following is my question re-worded

Reading the first 10 bytes of a binary file (operations later) -

infile = open('infile.jpg', 'rb')
outfile = open('outfile.jpg', 'wb')
x = infile.read(10)
for i in x:
    print(i, end=', ')
print(x)
outfile.write(bytes(x, "UTF-8"))

The first print statement gives -

255, 216, 255, 224, 0, 16, 74, 70, 73, 70, 

The second print statement gives -

b'\xff\xd8\xff\xe0\x00\x10JFIF'

a hexadecimal interpretation of the values in x.

outfile.write(bytes(x, "UTF-8"))

returns -

TypeError: encoding or errors without a string argument

Then x must not be a normal string but rather a byte string, which is still iterable?

If I want to write the contents of x to outfile.jpg unaltered then I go -

outfile.write(x)

Now I try to take each x [i] and perform some operation on each (shown below as a bone simple product of 1), assign the values to y and write y to outfile.jpg such that it is identical to infile.jpg. So I try -

infile = open('infile.jpg', 'rb')
outfile = open('outfile.jpg', 'wb')
x = infile.read(10)

yi = len(x)
y = [0 for i in range(yi)]

j = 0
for i in x:
    y [j] = i*1
    j += 1

for i in x:
    print(i, end=', ')

print(x)

for i in y:
    print(i, end=', ')

print(y)

print(repr(x))
print(repr(y))

outfile.write(y)

The first print statement (iterating through x) gives -

255, 216, 255, 224, 0, 16, 74, 70, 73, 70,

The second print statement gives -

b'\xff\xd8\xff\xe0\x00\x10JFIF'

The third print statement (iterating through y) gives -

255, 216, 255, 224, 0, 16, 74, 70, 73, 70,

The print statement gives -

[255, 216, 255, 224, 0, 16, 74, 70, 73, 70]

And finally, printing repr(x) and repr(y), as suggested by Tim, gives, respectively -

b'\xff\xd8\xff\xe0\x00\x10JFIF'
[255, 216, 255, 224, 0, 16, 74, 70, 73, 70]

And the file write statement gives the error -

TypeError: 'list' does not support the buffer interface

What I need is y to be the same type as x such that outfile.write(x) = outfile.write(y)

I stare into the eyes of the Python, but still I do not see its soul.

3 Answers
Related