3

I have a program that encrypts the contents of a file into cipher text. I want the program to write the ciphertext, that Is in a list, to a file.

The part of my code I need help with is:

for char in encryptFile:
    cipherTextList = []
    if char == (" "):
        print(" ",end=" ")
    else:
        cipherText = (ord(char)) + offsetFactor
    if cipherText > 126:
        cipherText = cipherText - 94
        cipherText = (chr(cipherText))
        cipherTextList.append(cipherText)
        for cipherText in cipherTextList:
                print (cipherText,end=" ")
    with open ("newCipherFile.txt","w") as cFile:
        cFile.writelines(cipherTextList)

The whole program runs smoothly, however the file that is called "newCipherFile.txt" only has one character in it.

I think this has something to do with the location of the empty list "cipherTextList = []", however I have tried moving this list out of the for loop, into the function, but when I print it the part that prints the ciphertext is in an infinite loop and prints the normal text over and over again.

Any help would be lovely.

iTzAlex F
  • 35
  • 3
  • possible duplicate of [How do you append to a file in Python?](http://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python) – Abhishek Apr 28 '15 at 09:25

2 Answers2

10

You keep overwriting opening the file with w so you only ever see the very last values, use a to append:

 with open("newCipherFile.txt","a") as cFile:

Or a better idea so to open it outside the loop once:

with open("newCipherFile.txt","w") as cFile:
    for char in encryptFile:
        cipherTextList = []
        ............
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

Use ("newCipherFile.txt","a") instead of ("newCipherFile.txt","w"). a is for append and w is for over-write.

Abhishek
  • 6,912
  • 14
  • 59
  • 85