str object doesn't support item assignment (when reading bytes)

2.4k Views Asked by At

I have two binary data files and I want to replace the contents of part of the second binary data file This is the sample code I have so far

Binary_file1 = open("File1.yuv","rb")
Binary_file2 = open("File2.yuv","rb")

data1 = Binary_file1.read()
data2 = Binary_file2.read()

bytes = iter(data1)

for i in range(4, 10):
    data2[i] = next(bytes)  

It fails at the part where I equate the data2[i] with next(bytes) and gives me an error saying that “'str' object does not support item assignment” The part I dont understand is that how is this a string object and how can I resolve this error ,Any help would be appreciated . PLease note the Binary files here are huge and I would like to avoid creating duplicate files as I alwyas will run into Memory Issues

2

There are 2 best solutions below

3
On

You opened file and read it. So, You have string in data2. Strings do not support item assignment.

Instead, You could do:

data2 = data[2][:i] + next(bytes) + data[2][i + 1:]
1
On

Strings cannot be changed inplace (i.e. they are immutable). Try this:

a = 'abcde'
a[2] = 'F'

You will get an error. But, this will work.

a = a.replace(a[2], 'F')

You might be better off building a new string, then slicing it into your data2.

newstring = ''
for i in range(4, 10):
    newstring += next(bytes)

data2 = data2.replace(data2[4:10], newstring)

Of course, the problem here is that data2[4:10] may not be unique within data2, in which case you will have multiple replacements. So, the following may be even better:

data2 = data2[:4] + newstring + data[10:]