How to write a list to a file in python
I have a program that encrypts the content of a file in cipher text. I want the program to write the cipher text that is in the list to a file.
Part of my code, I need help:
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, but the file called "newCipherFile.txt" has only one character.
I think it has to do with the location of the empty list "cipherTextList = []", however I tried to move this list from the for loop to the function, but when I print it, the part that prints the cipher text is in an infinite loop and prints the normal text again and again.
Any help would be great.
source to share
You save the overwrite by opening the file with w
so that you only ever see the most recent values, use a
to append:
with open("newCipherFile.txt","a") as cFile:
Or a better idea to open it outside of the loop once:
with open("newCipherFile.txt","w") as cFile:
for char in encryptFile:
cipherTextList = []
............
source to share