Я пытаюсь выяснить, как заставить Python читать содержимое файла .txt только один раз. Это для проекта класса для шифрования и дешифрования сообщения с использованием всех печатных символов ASCII. Делать это таким образом не обязательно. Это только моя четвертая программа, которую я написал на Python, и я действительно не знаю, что я делаю, но мне нравится пытаться придумать разные подходы к выполнению заданий. Я надеюсь, что я все правильно ввел здесь. Я знаю, что это легко исправить, я просто не смог найти ответ. Задание будет текущим проектом в течение следующих 6 недель. Мой план состоит в том, чтобы сделать шифрование намного более сложным (да, я знаю, что вы никогда не должны использовать Python для шифрования). Поэтому я пишу это, имея в виду более широкую картину.
Это, как говорится. Если кто-то хочет выйти за рамки ответа на мой вопрос, не стесняйтесь разорвать все на части. Дайте мне знать, что я сделал неправильно, почему, как я мог сделать это лучше. Я хотел бы получить обратную связь.
import random
print("1. Encrypt")
print("2. Decrypt")
print(" ")
selection = int(input("What would you like to do? [1,2]? "))
while selection == 1:
plainText = input('Enter the message you wish to encrypt: ')
# right now the program encrypts the string at random between 1 and 95.
# All of the printable ASCII characters.
# the code below is written for when I can take the parameters of 1-95
# off and any input will simply loop around.
distance = random.randint(1, 95)
if distance < 1 or distance > 95:
print('Try Again')
continue
else:
# saves the random integer or (key)
# directly to a file without the user seeing it.
f = open('..\\Desktop\\encryptPractice\\theKey.txt', 'w+')
for key in range(1):
number = distance
f.write(str(number))
f.close()
code = ""
for ch in plainText:
ordvalue = ord(ch)
ordvalue = ordvalue + distance
while ordvalue < 32:
ordvalue += 95
while ordvalue > 126:
ordvalue -= 95
code += chr(ordvalue)
# saves the encrypted message
# directly to a file without the user seeing it.
f = open('..\\Desktop\\encryptPractice\\theMessage.txt', 'w+')
for theMessage in range(1):
secret = code
f.write(str(secret))
f.close()
print('Your message has been saved to the file named theMessage.txt')
break
# This is the decryption block - OPTION
# 2.)*********************************************
while selection == 2:
"""
I want to simply be able to open the file with the 'encrypted'
message on it and then open the file with the 'key' on it and
have the program decrypt the message and save it back to the
same file.
Both of the solutions below cause the program to read the
'encrypted' message over and over and over and...you get it.
"""
f = open('..Desktop\\encryptPractice\\theMessage.txt','r')
for line in f:
print(line)
f = open('..Desktop\\encryptPractice\\theMessage.txt','r')
while True:
line = f.readline()
if line == ""
break
print(line)