Ask coding questions

← Back to all posts
file write problems
ThaddeasMarkle (0)

I've been working on a project that enciphers and deciphers text using the viginere cipher. My problem is with the encrypt_file() function. It reads the file fine, but at the part where it writes to the file, toencrypt.txt never changes. I downloaded the code as a .zip, and it worked as expected, so I know it's not a problem with my code. Here's a link to it though: https://repl.it/@ThaddeasMarkle/Viginere

Commentshotnewtop
malvoliothegood (106)

Better still, to make your program more robust change your encrypt_file function like so:

# This function takes  the contents of input_filename, encrypts it, and
# saves it in a newly created file called output_filename
# output_filename is created if it does not exist already
def encrypt_file(input_filename, output_filename, key='password', alph='abcdefghijklmnopqrstuvwxyz'):
    text = encrypted_from_file(input_filename, key, alph)

    file = open(output_filename, "w") 
    file.write(text) 
    file.close()

# Call the function like so:
input_filename = "toencrypt.txt"
output_filename = "encrypted_file.txt"
crypto.encrypt_file(input_filename,output_filename)
malvoliothegood (106)

Create an empty file called 'encrypted.txt' and use this code to write the encrypted text to it:

 with open('encrypted.txt', 'w') as file:
        file.write(text)