Python- f.write() 方法删除文本文件的先前内容
Python- f.write() method deletes previous content of a text file
我决定将文本文件读写添加到一个简单的加密程序中。
这个想法是,程序要求用户提供两个密钥和一个输入,它加密它们并将它们保存到一个文件中。
当用户想要检索内容时,程序会要求提供两个密钥并从文件中读取并对其进行解密。
所以,我让它工作了一次。问题是,我的程序会在用户加密后询问 'Continue Y/N'。如果他们说是,然后要求解密,它就可以正常工作。但是如果他们要求加密其他东西,它会覆盖文件以前的内容。
这很可能是问题所在,因为这是读取和写入发生的地方。
def User_Text_Interface(Repeat):
while Repeat == True:
f = open("COT.txt", "w+")
ED, Key, Key2, Temp = input("Do you want to encrypt or decrypt? "), input("Input a key- "), input("Input a second key- "), 0
if ED.lower() =="encrypt" or ED.lower() == "e":
User_Input = input("Input a string to " + str(ED) + "- ")
Key, Key2 = Compatibility(Key, User_Input), Compatibility(Key2,User_Input)
if ED.lower() == "encrypt" or ED.lower() == "e":
ET = str(Encrypt(User_Input, Key, Key2))
f.write(ET + "\n")
print("Your encrypted text is " + ET + " -it has been saved.")
elif ED.lower() == "decrypt" or ED.lower() == "d":
with open("COT.txt", "r+") as f:
for line in f:
print(str(Decrypt(line, Key, Key2)))
Repeat = input("Do you wish to continue? Y/N- ")
if Repeat.lower() == "yes" or Repeat.lower() == "y":
Repeat = True
else:
Repeat = False
我的其余代码供参考-
import time, sys, random
Master_Key = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#£$%&'()*+,-./:;?@[\]^_`{|}~"
## r+ means read and write
def Encrypt(User_Input, Key, Key2):
Output = ""
for i in range(len(User_Input)):
Ref_For_Output = Master_Key.index(User_Input[i]) + Master_Key.index(Key[i]) + Master_Key.index(Key2[i])
if Ref_For_Output >= len(Master_Key):
Ref_For_Output -= len(Master_Key)
Output += Master_Key[Ref_For_Output]
return Output
def Decrypt(User_Input, Key, Key2):
Output = ""
for i in range(len(User_Input)):
Ref_For_Output = Master_Key.index(User_Input[i]) - Master_Key.index(Key[i])- Master_Key.index(Key2[i])
if Ref_For_Output < 0:
Ref_For_Output += len(Master_Key)
Output += Master_Key[Ref_For_Output]
return Output
def Ordered_Test_Algorithm(Null):
for i in range(len(Master_Key)-1):
Input= Master_Key[i]
print("Input = " + Input)
for i in range(len(Master_Key)-1):
Key = Master_Key[i]
for i in range(len(Master_Key)-1):
Key2 = Master_Key[i]
Output = Decrypt(Encrypt(Input, Key, Key2), Key, Key2)
print("Encryption and decryption of Input- " + str(Input) + " with the Key- " + str(Key) + " and a second Key of " + str(Key2) + " results in an output of " + str(Output))
if Input == Output:
print("Pass")
else:
print("Fail")
sys.exit
print("Testing complete- Pass")
def Random_Test_Algorithm(Input_Length, Repeat_times):
for i in range(Repeat_times):
User_Input, Key, Key2 = "", "", ""
for i in range(Input_Length):
Input_ref, Key_ref, Key_2_Ref = random.randint(0, len(Master_Key)-1), random.randint(0, (len(Master_Key)-1)), random.randint(0, (len(Master_Key)-1))
User_Input += Master_Key[Input_ref]
Key += Master_Key[Key_ref]
Key2 += Master_Key[Key_2_Ref]
print("The randomly generated " + str(Input_Length) + " character input key and second key are " + User_Input + ", " + Key + " and " + Key2 +" respectively.")
print("The result of encryption is- " + Encrypt(User_Input, Key, Key2) )
print("The result of decryption is- " + Decrypt(Encrypt(Input, Key, Key2), Key, Key2) )
if User_Input == Decrypt(Encrypt(Input, Key, Key2), Key, Key2):
print("The encryption and decryption of " + User_Input + " with " + Key + " and " + Key2 + " was successful")
else:
print("The encryption and decryption of " + User_Input + " with " + Key + " and " + Key2 + " was un-successful")
sys.exit
def Compatibility(Key, User_Input):
Temp = 0
while Key == "":
print("Your key cannot be blank")
while len(Key) > len(User_Input):
Key = Key[:-1]
while len(Key) < len(User_Input):
Key += (Key[Temp])
Temp += 1
return Key
def User_Text_Interface(Repeat):
while Repeat == True:
f = open("COT.txt", "w+")
ED, Key, Key2, Temp = input("Do you want to encrypt or decrypt? "), input("Input a key- "), input("Input a second key- "), 0
if ED.lower() =="encrypt" or ED.lower() == "e":
User_Input = input("Input a string to " + str(ED) + "- ")
Key, Key2 = Compatibility(Key, User_Input), Compatibility(Key2,User_Input)
if ED.lower() == "encrypt" or ED.lower() == "e":
ET = str(Encrypt(User_Input, Key, Key2))
f.write(ET + "\n")
print("Your encrypted text is " + ET + " -it has been saved.")
elif ED.lower() == "decrypt" or ED.lower() == "d":
with open("COT.txt", "r+") as f:
for line in f:
print(str(Decrypt(line, Key, Key2)))
Repeat = input("Do you wish to continue? Y/N- ")
if Repeat.lower() == "yes" or Repeat.lower() == "y":
Repeat = True
else:
Repeat = False
print("This program can run three different sub-programs-")
print("1- Run the encryption and decryption sub-program specified in Unit A453- CAM 3.")
print("2- Run a test which encrypts and decrypts each ascii character with each other ascii character.")
print("3- Run a test which generates random inputs and keywords, before encrypting and decrypting them.")
Option = input("Please choose either 1, 2 or 3- ")
if Option == "1":
print("Running text based program-")
time.sleep(1)
User_Text_Interface(True)
elif Option == "2":
print("This test will encrypt and decrypt each keyboard character with every other keyboard character")
print("It will print around 1,860,000 lines of output, unless a decrypted value is not equal to its input, this will cause the test to stop")
print("Beginning test- ")
Ordered_Test_Algorithm("Null")
time.sleep(1)
elif Option == "3":
print("This test will generate a random input and keyword of a specified length using the random.randint function in the random module.")
print("It will then encrypt and decrypt the input with the keyword before checking if the output is equal to the input.")
print("The test will repeat a specifieed number of times.")
Input_Length = int(input("Input a numerical length (Length in characters e.g. 'Python' is 6 characters)for the key and keyword- "))
Repeat_times = int(input("Input the number of times the test should be repeated- "))
print("Beginning test- ")
time.sleep(1)
Random_Test_Algorithm(Input_Length, Repeat_times)
请注意,没有真正的错误,程序会写入一个名为 COT.txt 的 .txt 文件,它代表输出文本。老实说,我不记得c代表什么了。
不管怎样,这就是我想要它做的,但我希望它将每一行新的加密文本写入文件的一个新行。
使用 a+
文件模式追加内容而不是像 w+
那样覆盖。
f = open("COT.txt", "w+")
Write模式覆盖文件,你必须在a+
模式下打开它;
f = open("COT.txt", "a+")
或者只使用 with open()
方法更好。
with open("COT.txt","a+") as f:
f.write(something)
我决定将文本文件读写添加到一个简单的加密程序中。
这个想法是,程序要求用户提供两个密钥和一个输入,它加密它们并将它们保存到一个文件中。
当用户想要检索内容时,程序会要求提供两个密钥并从文件中读取并对其进行解密。
所以,我让它工作了一次。问题是,我的程序会在用户加密后询问 'Continue Y/N'。如果他们说是,然后要求解密,它就可以正常工作。但是如果他们要求加密其他东西,它会覆盖文件以前的内容。
这很可能是问题所在,因为这是读取和写入发生的地方。
def User_Text_Interface(Repeat):
while Repeat == True:
f = open("COT.txt", "w+")
ED, Key, Key2, Temp = input("Do you want to encrypt or decrypt? "), input("Input a key- "), input("Input a second key- "), 0
if ED.lower() =="encrypt" or ED.lower() == "e":
User_Input = input("Input a string to " + str(ED) + "- ")
Key, Key2 = Compatibility(Key, User_Input), Compatibility(Key2,User_Input)
if ED.lower() == "encrypt" or ED.lower() == "e":
ET = str(Encrypt(User_Input, Key, Key2))
f.write(ET + "\n")
print("Your encrypted text is " + ET + " -it has been saved.")
elif ED.lower() == "decrypt" or ED.lower() == "d":
with open("COT.txt", "r+") as f:
for line in f:
print(str(Decrypt(line, Key, Key2)))
Repeat = input("Do you wish to continue? Y/N- ")
if Repeat.lower() == "yes" or Repeat.lower() == "y":
Repeat = True
else:
Repeat = False
我的其余代码供参考-
import time, sys, random
Master_Key = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#£$%&'()*+,-./:;?@[\]^_`{|}~"
## r+ means read and write
def Encrypt(User_Input, Key, Key2):
Output = ""
for i in range(len(User_Input)):
Ref_For_Output = Master_Key.index(User_Input[i]) + Master_Key.index(Key[i]) + Master_Key.index(Key2[i])
if Ref_For_Output >= len(Master_Key):
Ref_For_Output -= len(Master_Key)
Output += Master_Key[Ref_For_Output]
return Output
def Decrypt(User_Input, Key, Key2):
Output = ""
for i in range(len(User_Input)):
Ref_For_Output = Master_Key.index(User_Input[i]) - Master_Key.index(Key[i])- Master_Key.index(Key2[i])
if Ref_For_Output < 0:
Ref_For_Output += len(Master_Key)
Output += Master_Key[Ref_For_Output]
return Output
def Ordered_Test_Algorithm(Null):
for i in range(len(Master_Key)-1):
Input= Master_Key[i]
print("Input = " + Input)
for i in range(len(Master_Key)-1):
Key = Master_Key[i]
for i in range(len(Master_Key)-1):
Key2 = Master_Key[i]
Output = Decrypt(Encrypt(Input, Key, Key2), Key, Key2)
print("Encryption and decryption of Input- " + str(Input) + " with the Key- " + str(Key) + " and a second Key of " + str(Key2) + " results in an output of " + str(Output))
if Input == Output:
print("Pass")
else:
print("Fail")
sys.exit
print("Testing complete- Pass")
def Random_Test_Algorithm(Input_Length, Repeat_times):
for i in range(Repeat_times):
User_Input, Key, Key2 = "", "", ""
for i in range(Input_Length):
Input_ref, Key_ref, Key_2_Ref = random.randint(0, len(Master_Key)-1), random.randint(0, (len(Master_Key)-1)), random.randint(0, (len(Master_Key)-1))
User_Input += Master_Key[Input_ref]
Key += Master_Key[Key_ref]
Key2 += Master_Key[Key_2_Ref]
print("The randomly generated " + str(Input_Length) + " character input key and second key are " + User_Input + ", " + Key + " and " + Key2 +" respectively.")
print("The result of encryption is- " + Encrypt(User_Input, Key, Key2) )
print("The result of decryption is- " + Decrypt(Encrypt(Input, Key, Key2), Key, Key2) )
if User_Input == Decrypt(Encrypt(Input, Key, Key2), Key, Key2):
print("The encryption and decryption of " + User_Input + " with " + Key + " and " + Key2 + " was successful")
else:
print("The encryption and decryption of " + User_Input + " with " + Key + " and " + Key2 + " was un-successful")
sys.exit
def Compatibility(Key, User_Input):
Temp = 0
while Key == "":
print("Your key cannot be blank")
while len(Key) > len(User_Input):
Key = Key[:-1]
while len(Key) < len(User_Input):
Key += (Key[Temp])
Temp += 1
return Key
def User_Text_Interface(Repeat):
while Repeat == True:
f = open("COT.txt", "w+")
ED, Key, Key2, Temp = input("Do you want to encrypt or decrypt? "), input("Input a key- "), input("Input a second key- "), 0
if ED.lower() =="encrypt" or ED.lower() == "e":
User_Input = input("Input a string to " + str(ED) + "- ")
Key, Key2 = Compatibility(Key, User_Input), Compatibility(Key2,User_Input)
if ED.lower() == "encrypt" or ED.lower() == "e":
ET = str(Encrypt(User_Input, Key, Key2))
f.write(ET + "\n")
print("Your encrypted text is " + ET + " -it has been saved.")
elif ED.lower() == "decrypt" or ED.lower() == "d":
with open("COT.txt", "r+") as f:
for line in f:
print(str(Decrypt(line, Key, Key2)))
Repeat = input("Do you wish to continue? Y/N- ")
if Repeat.lower() == "yes" or Repeat.lower() == "y":
Repeat = True
else:
Repeat = False
print("This program can run three different sub-programs-")
print("1- Run the encryption and decryption sub-program specified in Unit A453- CAM 3.")
print("2- Run a test which encrypts and decrypts each ascii character with each other ascii character.")
print("3- Run a test which generates random inputs and keywords, before encrypting and decrypting them.")
Option = input("Please choose either 1, 2 or 3- ")
if Option == "1":
print("Running text based program-")
time.sleep(1)
User_Text_Interface(True)
elif Option == "2":
print("This test will encrypt and decrypt each keyboard character with every other keyboard character")
print("It will print around 1,860,000 lines of output, unless a decrypted value is not equal to its input, this will cause the test to stop")
print("Beginning test- ")
Ordered_Test_Algorithm("Null")
time.sleep(1)
elif Option == "3":
print("This test will generate a random input and keyword of a specified length using the random.randint function in the random module.")
print("It will then encrypt and decrypt the input with the keyword before checking if the output is equal to the input.")
print("The test will repeat a specifieed number of times.")
Input_Length = int(input("Input a numerical length (Length in characters e.g. 'Python' is 6 characters)for the key and keyword- "))
Repeat_times = int(input("Input the number of times the test should be repeated- "))
print("Beginning test- ")
time.sleep(1)
Random_Test_Algorithm(Input_Length, Repeat_times)
请注意,没有真正的错误,程序会写入一个名为 COT.txt 的 .txt 文件,它代表输出文本。老实说,我不记得c代表什么了。
不管怎样,这就是我想要它做的,但我希望它将每一行新的加密文本写入文件的一个新行。
使用 a+
文件模式追加内容而不是像 w+
那样覆盖。
f = open("COT.txt", "w+")
Write模式覆盖文件,你必须在a+
模式下打开它;
f = open("COT.txt", "a+")
或者只使用 with open()
方法更好。
with open("COT.txt","a+") as f:
f.write(something)