Ok so I made this simple encryption program (I am new to python) that encrypts every file in the directory it is being used (For learning purposes). Here's the code:
import os
import time
txts = list()
for i in os.listdir():
if i.endswith('.txt'):
txts.append(i)
for i in txts:
filer = open(i, 'r')
st = str()
for j in filer.read():
st = chr(ord(j) 2)
filew = open(i,'w')
filew.write(st)
def decrypt():
for i in txts:
filer = open(i, 'r')
st = str()
for j in filer.read():
st = chr(ord(j)-2)
filew = open(i,'w')
filew.write(st)
So my problem is: It encrypts every single file txt file in the directory, besides the last one, always. The last file always gets overwritten with nothing, unlike all the others, no matter what txt is the last file. Ive checked the txts list and All the txt files in the directory. But the last file, just doesnt want to get encrypted. Lets say I put abcd in the file, after my program runs in the file there won't be a single thing.
CodePudding user response:
Ok so I got it working by putting the code that encrypts the file in a function, and then calling that function, but can anyone tell me why wasn't it working for the last file before
CodePudding user response:
When you put the "encryption" code in a function, the file objects returned by open
go out of scope and are garbage collected. Part of that process for file objects is flushing write buffers and closing the files.
According to the documentation:
Warning: Calling
f.write()
without using thewith
keyword or callingf.close()
might result in the arguments off.write()
not being completely written to the disk, even if the program exits successfully.