Mr.Code
Mr.Code

Reputation: 9

How to decompress a file using python 3.x and gzip

I have had help creating a piece of code that compresses a input from a user.The code then transfers this compressed version into a file. The code also sends the input into a file to see how much the file has been compressed.

import gzip, time

plaintext = input("Please enter the text you want to compress: ")
file_ = open('text.txt', 'w')
file_.write(str(plaintext))
file_.close()
with gzip.open('compressed_file.text' + ".gz", "wb") as outfile:
    outfile.write(bytes(plaintext, 'UTF-8'))


with open("data.txt","wb") as fh:
    with open('compressed_file.text.gz', 'rb') as fd:
        fh.write(fd.read())

I want some help on how to decompress the file to make the original user input.

Upvotes: 0

Views: 5123

Answers (2)

Mr.Code
Mr.Code

Reputation: 9

This is the answer as I found it on the answer to another question.

plaintext = input('Please enter some text')
filename = 'foo.gz'
with gzip.open(filename, 'wb') as outfile:
    outfile.write(bytes(plaintext, 'UTF-8'))
with gzip.open(filename, 'r') as infile:
    outfile_content = infile.read().decode('UTF-8')
print(outfile_content)

This compresses the input, stores it in the a file and also decompress the file to make the original input. This decompressed input is then printed to the shell.

Upvotes: 0

Dinesh Pundkar
Dinesh Pundkar

Reputation: 4194

I think, just reading GZIP file and writing back to file will help you.

import gzip

plaintext = input("Please enter the text you want to compress: ")

with open("text.txt","wb") as file_:
    file_.write(str(plaintext.encode('utf-8')))

filename = input("Please enter the desired filename: ")
print("Name of file to be zipped is text.txt")
print("Name of GZIP file is ",filename+'.gz')
print("Zipping file...")
with gzip.GzipFile(filename + ".gz", "wb") as outfile:
    outfile.write(open("text.txt").read())

print("Name of unzipped file is unzip_text.txt")
print("Unzipping ...")
with gzip.GzipFile(filename + ".gz", 'rb') as inF:
    with file("unzip_text.txt", 'wb') as outF:
        s = inF.read()
        outF.write(s.encode('utf-8'))

print("Content of unzip file is...")
with open("unzip_text.txt") as fd:
    for line in fd.readlines():
        print line

Output :

C:\Users\dinesh_pundkar\Desktop>python gz.py
Please enter the text you want to compress: "My name is Dinesh"
Please enter the desired filename: "dinesh"
Name of file to be zipped is text.txt
('Name of GZIP file is ', 'dinesh.gz')
Zipping file...
Name of unzipped file is unzip_text.txt
Unzipping ...
Content of unzip file is...
My name is Dinesh

C:\Users\dinesh_pundkar\Desktop>

Upvotes: 2

Related Questions