简体   繁体   English

Python-在每次while循环重复后写入文本文件的新行

[英]Python- Write to a new line of a text file after each repeat of a while loop

I am trying to save the output of a basic encryption program to a text file. 我正在尝试将基本加密程序的输出保存到文本文件。 It works, the problem is that it saves each new output right next to the last without a space, or a new line (What I want). 它起作用了,问题在于它将每个新输出保存在最后一个紧挨着的末尾,没有空格或换行(我想要的是)。

I would like the user to be able to choose a line to read from and decrypt rather than decrypting the whole lot. 我希望用户能够选择要读取和解密的行,而不是解密全部内容。

Currently I get this- 目前,我得到这个-

This program can run three different sub-programs-
1- Run the encryption and decryption sub-program specified in Unit A453- CAM 3.
2- Run a test which encrypts and decrypts each ascii character with each other ascii character.
3- Run a test which generates random inputs and keywords, before encrypting and decrypting them.
Please choose either 1, 2 or 3- 1
Running text based program-
Do you want to encrypt or decrypt? encrypt
Input a key- abc
Input a second key- 123
Input a string to encrypt- Theo
Your encrypted text is %vuA -it has been saved.
Do you wish to continue? Y/N- y
Do you want to encrypt or decrypt? encrypt
Input a key- 123
Input a second key- abc
Input a string to encrypt- Theo
Your encrypted text is %vuA -it has been saved.
Do you wish to continue? Y/N- y
Do you want to encrypt or decrypt? 

So as you can see I have done the same thing twice (Ignore the fact that reversing the encryption keys does nothing- I haven't actually written a proper algorithm for their use, it just adds them on) 因此,如您所见,我已经做过两次相同的事情(忽略以下事实:反转加密密钥没有任何作用-我实际上没有编写适当的算法来使用它们,只是添加了它们)

The text file looks like this- 文本文件看起来像这样-

%vuA%vuA

I am trying to get it to do this- 我正在努力做到这一点-

%vuA
%vuA

Finally another thing. 最后是另一回事。 Not so much a problem but a 'What the hell, why?!' 并不是什么大问题,而是“什么鬼,为什么?!” is that the text is not written to the text file until I pick Y or N in the 'do you wish to continue. 是直到我在“您想继续吗?”中选择Y或N之前,文本才被写入文本文件。

The specific bit of code doing the reading and writing is this function- 进行读取和写入的代码的特定位是此功能-

def User_Text_Interface(Repeat):
    while Repeat == True:
        f = open("COT.txt", "a+")
        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((Encrypt(User_Input, Key)), Key2))
            f.write(ET)
            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((Decrypt((Encrypt((Encrypt(User_Input, Key)), Key2)), Key2)), Key)))
        Repeat = input("Do you wish to continue? Y/N- ")
        if Repeat.lower() == "yes" or Repeat.lower() == "y":
            Repeat = True
        else:
            Repeat = False 

The rest of my code, most of which can be ignored as it is superfluous- 我的其余代码,其中大部分可以忽略,因为它是多余的-

import time, sys, random
Master_Key = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#£$%&'()*+,-./:;?@[\\]^_`{|}~"

def Encrypt(User_Input, Key):
    Output = ""
    for i in range(len(User_Input)):
        Ref_For_Output = Master_Key.index(User_Input[i]) + Master_Key.index(Key[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):
    Output = ""
    for i in range(len(User_Input)):
        Ref_For_Output = Master_Key.index(User_Input[i]) - Master_Key.index(Key[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", "a+")
        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((Encrypt(User_Input, Key)), Key2))
            f.write(ET)
            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((Decrypt((Encrypt((Encrypt(User_Input, Key)), Key2)), Key2)), Key)))
        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)

In line 77, change 在第77行中,更改

f.write(ET)

to

f.write(ET + "\n")

and at line 88, insert 然后在第88行插入

f.flush()    # force it to write buffered output

(make sure it is indented, inside the while Repeat == True: loop.) (确保它在while Repeat == True:循环内缩进)。

while Repeat == True: is redundant; while Repeat == True:是多余的; you can just do while repeat: ; 您可以while repeat: and line 70 ( f = open("COT.txt", "a+") ) can be moved to precede the loop (you only need to open the file once, not once per loop). 并可以将第70行( f = open("COT.txt", "a+") )移到循环之前(您只需要打开一次文件,而不是每个循环一次)。

and Stop Using InitialCaps For Your Variable Names! 并停止为变量名使用InitialCaps! :-P :-P


Edit : 编辑

I just noticed, in Ordered_Test_Algorithm you reuse the index variable i (lines 25, 28, 30); 我只是注意到,在Ordered_Test_Algorithm您重用了索引变量i (第Ordered_Test_Algorithm行); this will not work and will cause you many headaches. 这将不起作用,并且会引起您很多头痛。 Try using a different variable for each for loop! 尝试为每个for循环使用不同的变量!

On line 32, you are trying to call encrypt and decrypt with three arguments; 在第32行,您尝试使用三个参数调用encryptdecrypt but they are only two-argument functions. 但它们只是两个参数的函数。

Also, you have a very C++ish coding style; 同样,您有一种非常C ++的编码风格。 I see a lot of 我看到很多

for i in range(len(Master_Key)-1):  # off-by-1 error; do not subtract 1 from end of range
    Input= Master_Key[i]

where the Pythonic method would be Pythonic方法将在哪里

for ch in Master_Key:

Also, your encrypt and decrypt logic just assumes that len(Key) >= len(User_Input) ; 同样,您的encryptdecrypt逻辑只是假设len(Key) >= len(User_Input) ; if this is not so, your functions will fail with an IndexError . 如果不是这样,则您的函数将失败,并显示IndexError

I can't take the time to analyze your code, but you should: 我无法花时间分析您的代码,但是您应该:

1. Open the file in a+ which you have already done.
2. Immediately call myfile.write('\n') after input. 
3. Close the file to press changes.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM