Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypting the lines in a file

Tags:

python

I'm trying to write a program that opens a text file, and shifts each of the characters in the file 5 characters to the right. It should only do this for alphanumeric characters, and leave nonalphanumerics as they are. (ex: C becomes H) I'm supposed to be using the ASCII table to do this, and I'm having an issue when the characters wrap around. ex: w should become b, but my program gives me a character that's in the ASCII table. Another issue I'm having is that all the characters are printing on separate lines and I'd like them all to print on the same line. I can't use lists or dictionaries.

This is what I have, I'm not sure how to do the final if statement

def main():
    fileName= input('Please enter the file name: ')
    encryptFile(fileName)


def encryptFile(fileName):
    f= open(fileName, 'r')
    line=1
    while line:
       line=f.readline()
       for char in line:
           if char.isalnum():
               a=ord(char)
               b= a + 5
               #if number wraps around, how to correct it
               if 

                print(chr(c))
            else:
                print(chr(b))
        else:
            print(char)
like image 211
tinydancer9454 Avatar asked Feb 17 '23 07:02

tinydancer9454


1 Answers

Using str.translate:

In [24]: import string

In [25]: string.uppercase
Out[25]: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

In [26]: string.uppercase[5:]+string.uppercase[:5]
Out[26]: 'FGHIJKLMNOPQRSTUVWXYZABCDE'

In [27]: table = string.maketrans(string.uppercase, string.uppercase[5:]+string.uppercase[:5])

In [28]: 'CAR'.translate(table)
Out[28]: 'HFW'

In [29]: 'HELLO'.translate(table)
Out[29]: 'MJQQT'
like image 154
unutbu Avatar answered Feb 19 '23 19:02

unutbu