I have written a file compressor in python. The program generates a file filled with sequences of the same character with a random length, and compresses that file. I would like feedback on code readability, efficiency, and any other nitpicks that you find. Any and all feedback is considered and appreciated!
compress.py
""" Import Statements """
import os
import random
import re
import string
UNCOMPRESSED_FILE = "code/python/compression/uncompressed.txt"
COMPRESSED_FILE = "code/python/compression/compressed.txt"
RE_UNCOMPRESSED_FILE = "code/python/compression/re_uncompressed.txt"
def get_random_letter(previous_letter):
""" Gets a letter that isn't the previous letter """
letter = random.choice(string.ascii_lowercase)
return letter if letter != previous_letter else get_random_letter(previous_letter)
def generate_file():
""" Generates file to be compressed """
previous_letter = "A"
with open(UNCOMPRESSED_FILE, "w") as file:
for _ in range(random.randint(10000, 100000)):
letter = get_random_letter(previous_letter)
for _ in range(random.randint(3, 9)):
file.write(letter)
previous_letter = letter
def compress_file(file_to_be_compressed):
""" Creates a new compressed file from the past file """
compressed_string = ""
characters = file_to_list(file_to_be_compressed)
count = 0
for i in range(len(characters)):
try:
if characters[i] == characters[i + 1]:
count += 1
else:
compressed_string += f"{characters[i]}{count + 1}"
count = 0
except IndexError:
if characters[len(characters) - 1] == characters[len(characters) - 2]:
count += 1
compressed_string += f"{characters[i]}{count}"
with open(COMPRESSED_FILE, "w") as compressed_file:
compressed_file.write(compressed_string)
def decompress_file(file_to_be_decompressed):
""" Decompresses passed file """
compressed_content = file_to_one_line(file_to_be_decompressed)
decompressed_content = re.findall("..", compressed_content)
#print(decompressed_content)
with open(RE_UNCOMPRESSED_FILE, "w") as re_uncompressed_file:
for pair in decompressed_content:
letter = pair[0]
num = int(pair[1])
re_uncompressed_file.write(letter * num)
def get_file_size(file):
""" Returns the file size, in bytes """
return os.path.getsize(file)
def file_to_one_line(file):
""" Concats all lines in file to one line """
with open(file, "r") as file_to_read:
lines = ""
for line in file_to_read:
lines += line
return line
def file_to_list(file):
""" Converts all the lines into an array of characters"""
with open(file, "r") as file_to_read:
lines = ""
for line in file_to_read:
lines += line
return list(map(str, lines))
if __name__ == '__main__':
generate_file()
print(f"File size before compression: {get_file_size(UNCOMPRESSED_FILE)}")
compress_file(UNCOMPRESSED_FILE)
print(f"File size after compression: {get_file_size(COMPRESSED_FILE)}")
decompress_file(COMPRESSED_FILE)
print(f"File size after decompression: {get_file_size(RE_UNCOMPRESSED_FILE)}")