Input data to the program from file & save data to file.

Most programs need some sort of input. Our enciphering program needed the message and the key. So far I have made these inputs by pasting or typing them into the program.

An alternative is to paste the text into an ordinary text file and make the program read the file. This method avoids a possible corruption of the program when typing in the message.

So, for example, we paste, or type, a message into a file called ‘plaintext.txt’ located in the same directory as our program. Then the following program lines will open the file and read the contents into a string called 'message' and then print out the message.

filename = 'plaintext.txt'
fileid = open(filename,”r”) #...’r’ is for “read”
message=fileid.read()
fileid.close()

The same structure is used for saving the cipher created by the program. Below I've demonstrated this with a pretend piece of ciphertext.

ciphertext ='ABCDE FGHIJ KLMNO PQRST UVWXY Z'
filename = "cipher.txt"
fileid = open(filename,"w") #...”w” is for “write”
fileid.write(ciphertext)
fileid.close()

If you type this little program into Idle|File|New Window and press F5 to run it, you will find a new file 'cipher.txt' has been created in your directory and that it includes the pretend ciphertext.

PREVIOUS          NEXT