0

I am reading file in binary mode using python and it is working perfectly. I tried to update the content and the save it into a new file. The code's below:

def main():
    f = open("inputFile", "rb")
    myFile = f.read()
    outFile = myFile
    for i in range(0, len(myFile)):
        d1 = myFile[i] + 1
        outFile[i] = d1
    f2 = open("otFile", "wb")
    f2.write(outFile)
    f2.close()

The error is:

outFile[i] = d1
TypeError: 'bytes' object does not support item assignment

I tried

outFile[i] = bytes(d1)

I've got this error:

TypeError: 'bytes' object does not support item assignment
martineau
  • 119,623
  • 25
  • 170
  • 301
Faraji
  • 1
  • Does this answer your question? [Item assignment on bytes object in Python](https://stackoverflow.com/questions/1934624/item-assignment-on-bytes-object-in-python) – funie200 Sep 10 '20 at 10:10
  • A binary if is _encoded_. So you need to specify how the number value should be encoded. – monkut Sep 10 '20 at 10:11
  • https://stackoverflow.com/questions/606191/convert-bytes-to-a-string – Zhubei Federer Sep 10 '20 at 10:12

2 Answers2

0

Use bytearray() to convert the infile which gives the functionality of both reading and writing as well

def main():
    f = open("infile", "rb")
    myFile = f.read()
    outFile = bytearray(myFile)
    for i in range(0, len(myFile)): 
        d1 = myFile[i] + 1
        outFile[i] = d1
    f2 = open("outfile", "wb")
    f2.write(outFile)
    f2.close()
think-maths
  • 917
  • 2
  • 10
  • 28
0

I think you can just to something like this:

def main():
    f = open("inputFile", "rb")
    myFile = f.read()
    f.close()
    outFile = myFile
    for i in range(0, len(myFile)):
        d1 = myFile[i] + 1
        outFile += bytes(d1)
    f2 = open("otFile", "wb")
    f2.write(outFile)
    f2.close()

main()