Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-f.write()方法删除文本文件以前的内容_Python_File_Encryption_Text_Output - Fatal编程技术网

Python-f.write()方法删除文本文件以前的内容

Python-f.write()方法删除文本文件以前的内容,python,file,encryption,text,output,Python,File,Encryption,Text,Output,我决定将文本文件读写添加到一个简单的加密程序中 其思想是,程序要求用户提供两个密钥和一个输入,然后对它们进行加密并将其保存到文件中 当用户想要检索内容时,程序会要求获取两个密钥,并从文件中读取解密的内容 所以,我有一次让它工作。问题是,我的程序会在用户加密后询问用户“是否继续”。如果他们说是,然后要求解密,它就可以正常工作。但如果他们要求加密其他内容,则会覆盖文件先前的内容 这很可能是问题所在,因为这是阅读和写作发生的地方 def User_Text_Interface(Repeat):

我决定将文本文件读写添加到一个简单的加密程序中

其思想是,程序要求用户提供两个密钥和一个输入,然后对它们进行加密并将其保存到文件中

当用户想要检索内容时,程序会要求获取两个密钥,并从文件中读取解密的内容

所以,我有一次让它工作。问题是,我的程序会在用户加密后询问用户“是否继续”。如果他们说是,然后要求解密,它就可以正常工作。但如果他们要求加密其他内容,则会覆盖文件先前的内容

这很可能是问题所在,因为这是阅读和写作发生的地方

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)
导入时间,系统,随机
Master_Key=“0123456789 abcdefghijklmnopqrstuvwxyzabefghijklmnopqrstuvwxyz!\”“@[\\]^_`{|}~"
##r+表示读写
def加密(用户输入、密钥、密钥2):
Output=“”
对于范围内的i(len(用户输入)):
输出参考=主密钥索引(用户输入[i])+主密钥索引(密钥[i])+主密钥索引(密钥2[i]))
如果输出的Ref\U>=len(主\U键):
Ref_用于_输出-=len(主_键)
输出+=主控键[Ref\u用于\u输出]
返回输出
def解密(用户输入,密钥,密钥2):
Output=“”
对于范围内的i(len(用户输入)):
Ref_For_Output=主密钥索引(用户输入[i])-主密钥索引(密钥[i])-主密钥索引(密钥2[i]))
如果输出的参考值小于0:
Ref_用于_输出+=len(主_键)
输出+=主控键[Ref\u用于\u输出]
返回输出
def有序测试算法(空):
对于范围内的i(len(主钥匙)-1):
输入=主控键[i]
打印(“输入=”+输入)
对于范围内的i(len(主钥匙)-1):
密钥=主密钥[i]
对于范围内的i(len(主钥匙)-1):
键2=主控键[i]
输出=解密(加密(输入,密钥,密钥2),密钥,密钥2)
打印(“加密和解密输入-”+str(输入)+”,密钥为-“+str(密钥)+”,第二个密钥为“+str(密钥2)+”,结果输出“+str(输出))
如果输入=输出:
打印(“通行证”)
其他:
打印(“失败”)
系统出口
打印(“测试完成-通过”)
def随机测试算法(输入长度、重复次数):
对于范围内的i(重复\u次):
用户输入,键,键2=“”,“”“
对于范围内的i(输入长度):
输入\u ref,Key\u ref,Key\u 2\u ref=random.randint(0,len(Master\u Key)-1),random.randint(0,(len(Master\u Key)-1)),random.randint(0,(len(Master\u Key)-1))
用户输入+=主按键[输入参考]
钥匙+=主钥匙[钥匙参考]
按键2+=主按键[按键2\u参考]
打印(“随机生成的“+str(输入长度)+”字符输入键和第二个键分别为“+User_输入+”、“+key+”和“+Key2+”)
打印(“加密结果为-”+加密(用户输入,密钥,密钥2))
打印(“解密的结果是-”+解密(加密(输入,密钥,密钥2),密钥,密钥2))
如果用户输入=解密(加密(输入,密钥,密钥2),密钥,密钥2):
打印(“使用“+Key+”和“+Key2+”对“+User_Input+”进行加密和解密成功”)
其他:
打印(“使用“+Key+”和“+Key2+”对“+User_Input+”进行加密和解密未成功”)
系统出口
def兼容性(密钥、用户输入):
温度=0
while Key==“”:
打印(“您的密钥不能为空”)
当len(键)>len(用户输入)时:
键=键[:-1]
当len(键)f = open("COT.txt", "w+")
f = open("COT.txt", "a+")
with open("COT.txt","a+") as f:
    f.write(something)