In [1]:
import random

def compute_rand_key():
    rand_num = [0]*9
    for i in range(9):
        rand_num[i] = random.randint(0,9)
    return rand_num

def compute_rand_letter():
    rand_letter = random.randint(65,122)
    while rand_letter >= 91 and rand_letter <= 96:
        rand_letter = random.randint(65,122)
    return rand_letter

def encode(rand_key,word_len):
    file_in = open('F:\\python\\510test.txt','r')
    file_out = open('F:\\python\\510test_new_out.txt','w')
    for line in file_in:
        line = line.split()
        for word in line:
            word_len.append(len(word))
            key = rand_key.copy()
            key.append(len(word))
            word_new = []
            for i in range(len(word)):
                ascii_i = ord(word[i])
                ascii_i += int(key[i])
                if ascii_i>122:
                    ascii_i -= 57
                ascii_i = chr(ascii_i)
                word_new.append(ascii_i)
            for j in range(len(word),10):   # len(word)要如何保存下来
                rand_le = compute_rand_letter()
                word_new.append(chr(rand_le))
            word_new = "".join(word_new)
            file_out.write(word_new+' ')
    file_in.close()
    file_out.close()

def decode(rand_key,word_len):
    file_in = open('F:\\python\\510test_new_out.txt','r')
    file_out = open('F:\\python\\510test_old_out.txt','w')
    for line in file_in:
        print (line+'\n解密后的文件:')
        line = line.split()
        j = 0
        for word_new in line:
            rand_key.append(len(word_new))   ###如何得到原来的len(word)即字符的长度
            key = rand_key.copy()
            word_old = []
            for i in range(int(word_len[j])):
                ascii_i = ord(word_new[i])
                ascii_i -= int(key[i])
                if ascii_i<65:
                    ascii_i =122 -(int(key[i])- (ord(word_new[i]) - 65) ) 
                ascii_i = chr(ascii_i)
                word_old.append(ascii_i)

            word_old = "".join(word_old)
            j += 1
            print (word_old,end = ' ')
            file_out.write(word_old+' ')
    file_in.close()
    file_out.close()

def main():
    file_in = open('F:\\python\\510test.txt','r')
    print ('原来的文件:')
    for line in file_in:
        print (line)
    word_len = []
    rand_key = compute_rand_key()
    encode(rand_key,word_len)
    print ('后来的文件:')
    decode(rand_key,word_len)
    

if __name__ == '__main__':
    main()


原来的文件:
South African Duo Amis to be First to Row Across Southern Atlantic
后来的文件:
ZwDziKrsJl HnzodcpwdN KDwSYOmXXn HuqywIEqRa BwfGwSBooB imhgoYRZIe MqzyudPZBO BwTGLYzLDq YwFfolsJaq HkzutucqbI ZwDzigtvlg HCtgovkkcy 
解密后的文件:
South African Duo Amis to be First to Row Across Southern Atlantic