C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: We open the source file and then open an output file. We then apply the gzip open() method to write the compressed file.
Tip: The with statement is helpful here. This statement ensures that system resources are properly freed.
Python program that uses gzip
import gzip
# Open source file.
with open("C:\Codex.txt", "rb") as file_in:
# Open output file.
with gzip.open("C:\Codex.gz", "wb") as file_out:
# Write output.
file_out.writelines(file_in)
Output
Codex.txt size: 4404 bytes
Codex.gz size: 2110 bytes
And: In the output, we find the original file length is the same. No data was lost. We also have the file, in string format, in memory.
So: Instead of written the decompressed file to disk and reading that in, we can directly use the string contents.
Python program that decompresses file
import gzip
# Use open method.
with gzip.open("C:\Codex.gz", "rb") as f:
# Read in string.
content = f.read()
# Print length.
print(len(content))
Output
4404