import random def gen_key(): al = 'a ą b c ć d e ę f g h i j k l ł m n ń o ó p r s ś t u w y z ź ż'.split() alshuffled = al[:] random.shuffle(alshuffled) keymap = dict(zip(al, alshuffled)) return keymap def coded(char, key): upper = char.isupper() try: outchar=key[char.lower()] except KeyError: outchar = char if upper: outchar = outchar.upper() return outchar if __name__ == '__main__': key = gen_key() with open('key.txt', 'w', encoding="utf-8") as keyf: keyf.write(str(key)) with open('dokodowania.TXT', encoding="utf-8") as f: with open('coded.txt', 'w', encoding="utf-8") as fout: for line in f: newline = [] for char in line: newline.append(coded(char, key=key)) fout.write(''.join(newline))