Josef R Josef R - 1 month ago 9
Python Question

Converting .txt file into a table of characters in Python 3

Have a little problem here:

Trying to create my own "Aplhabet", which I want to apply on my .txt,.doc,.odt documents to encrypt them.

I wanted to ask, how could I convert the .txt,.doc,.odt file into a list of character, so I can then change them one by one for my own "Alphabets" characters.
And then convert them back again and save them.

I was trying to use:

c = ('test.txt')

with open(c, 'w', encoding='utf-8') as a_file:
#Here I was trying writing the entry right into the code to be written into the file
a_file.write('Neco jineho napsaneho')
for i, v in enumerate(c):
c[i] = v.replace("N", "3")

with open(c, encoding='utf-8') as a_file:
print(a_file.read())


But since the "c" is a .txt file and not a list, it wount work and just gives me this error:

c[i] = v.replace("N", "5")
TypeError: 'str' object does not support item assignment


Any help would be appreciated!

Cheers,

J

Answer

First, doing this

with open(c, 'w', encoding='utf-8') as a_file:

destroys your file contents right away. You have to read it fully before writing it back

Second, for i, v in enumerate(c): is iterating on the filename. Cannot work! (which explains the error you're getting: you're trying to encrypt the filename in place: strings are immutable). Anyway, not what you want to do...

And you don't need enumerate. Just create a list using listcomp while iterating on the file (file lines)

with open(c, 'r', encoding='utf-8') as a_file:
   lines = [v.replace("N", "3") for v in a_file]

# now write the "encrypted" file back using the same name
with open(c, 'w', encoding='utf-8') as a_file:
   a_file.write('Neco jineho napsaneho')
   a_file.writelines(lines)

Note: replace v.replace("N", "3") by a custom encrypt(v) if you want a more complex encryption.

lines = [encrypt(v) for v in a_file]

with encrypt defined as:

def encrypt(v):
     return v.replace("N","3").replace("Z","5")

(not very efficient, but it's just an example. With a dictionary it would be better)