'ValueError: write() requires mode 'w', 'x', or 'a' in Python zipfile

I am trying to open a specific file in the archive and then write some content to it. I am using the zipfile.open() function to get access to the file:

import zipfile


my_zip = zipfile.ZipFile('D:\\files\\acrhive.zip')

with my_zip.open('hello.txt', 'w') as my_file:
     my_file.write(b'Hello')
        
my_zip.close()

However, it gives me a warning about duplicate file called 'hello.txt'. After that I get the following error:

ValueError: write() requires mode 'w', 'x', or 'a'

What am I doing wrong here?

My full traceback:

D:\python\lib\zipfile.py:1506: UserWarning: Duplicate name: 'hello.txt'
  return self._open_to_write(zinfo, force_zip64=force_zip64)
Traceback (most recent call last):
  File "D:\files\python.py", line 8, in <module>
    with my_zip.open(file, 'w') as my_file:
  File "D:\python\lib\zipfile.py", line 1506, in open
    return self._open_to_write(zinfo, force_zip64=force_zip64)
  File "D:\python\lib\zipfile.py", line 1598, in _open_to_write
    self._writecheck(zinfo)
  File "D:\python\lib\zipfile.py", line 1699, in _writecheck
    raise ValueError("write() requires mode 'w', 'x', or 'a'")
ValueError: write() requires mode 'w', 'x', or 'a'


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source