How to read, write and compress text file in Python

In this tutorial we will create examples how to read text file and gzip file. We will also create a text file and compress or gzip file. The gzip file or compressed file extension is gz.

Prerequisites

Python 3.8.1

Import Module

Import required module as a first step in the Python script.

import os, gzip

Read File

The below function read either compressed or gzip (gz) text file or uncompressed text file depending upon the value True or False of the parameter compress. You can pass the file name with full path from where the file will be read. If you pass only file name then it will find the file in the Python script’s current directory.

If you need to know the current directory path then you can find using the function os.getcwd().

def read_file(fname, compress=False):
    if compress:
        f = gzip.GzipFile(fname, 'rb')
    else:
        f = open(fname, 'rb')
    try:
        data = f.read()
    finally:
        f.close()
    return data

Write File

The below function write to uncompressed text file or compressed or gzip (gz) text file. You must pass the file name with full path. If you pass only file name without any path then the file will be written into the Python script’s currect directory.

def write_file(data, fname, compress=True):
    #print(os.getcwd())

    if compress:
        f = gzip.GzipFile(fname, 'wb')
    else:
        f = open(fname, 'wb')
    try:
        f.write(data)
    finally:
        f.close()

Testing

data = read_file('hey.txt')
print(data)

data = read_file('hey.gz', True)
print(data)

write_file(b'This is a hello string', 'hello.txt', False)
write_file(b'This is a hello string in compress format', 'hello.txt.gz')

The content of hey.txt file is

hey, how are you?

The hey.gz file contains the hey.txt file.

Executing the Python script will give you below output in the console:

file read write compress (gzip)

Two files will be created in your Python’s current directory – hello.txt and hello.txt.gz.

Download

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *