Python3 gzip create new file which did not exist yet

Viewed 310

I struggle with python3.9, maybe I'm just blind, so give me a hint please.

Accoring to documententation the following code should create a ".gz"-file.

import gzip
content = b"Lots of content here"
with gzip.open('/home/joe/file.txt.gz', 'wb') as f:
    f.write(content)

Is it correct to assume that the file file.txt.gz does not exist before that operation and it will be created during that operation?

My code looks like:

import gzip

...
class FileHandler:

...

    def archive(self):
        self.content = 'Hello compressed World'
        zipFile = '/home/user/archive/test.gz'
        print(f'{zipFile}')
        with gzip.open(zipFile, 'wt') as f:
            f.write(self.content)
...

if __name__ == '__main__':
    fp = FileHandler()
    fp.archive()

I get the following exception:

Traceback (most recent call last):
  File "/home/user/filehandling.py", line 55, in <module>
    fp.archive()
  File "/home/user/filehandling.py", line 46, in archive
    with gzip.open(zipFile, 'wt') as f:
  File "/usr/lib/python3.9/gzip.py", line 58, in open
    binary_file = GzipFile(filename, gz_mode, compresslevel)
  File "/usr/lib/python3.9/gzip.py", line 173, in __init__
    fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '/home/user/archive/test.gz'

Obvisiously the file does not exist. Why is it not created as mentioned in the documentation? So what I am doing wrong here?

---- SOLVED ---- @Czaporka is right, I was missing a part of the path

0 Answers
Related