i am opening a csv file:
def get_file(start_file): #opens original file, reads it to array
with open(start_file,'rb') as f:
data=list(csv.reader(f))
header=data[0]
counter=collections.defaultdict(int)
for row in data:
counter[row[10]]+=1
return (data,counter,header)
does the file stay in memory if i quit the program inside the WITH
loop?
what happens to the variables in general inside the program when i quit the program without setting all variables to NULL
?
Apart from the risk of running into the limit, keeping files open leaves you vulnerable to losing data. In general, Python and the operating system work hard to protect you from data loss. But if your program—or computer—crashes, the usual routines may not take place, and open files can get corrupted.
Though Python automatically closes a file if the reference object of the file is allocated to another file, it is a standard practice to close an opened file as a closed file reduces the risk of being unwarrantedly modified or read.
Python doesn't flush the buffer—that is, write data to the file—until it's sure you're done writing, and one way to do this is to close the file. If you write to a file without closing, the data won't make it to the target file.
Using a with open() statement will automatically close a file once the block has completed. Not only will using a context manager free you from having to remember to close files manually, but it will also make it much easier for others reading your code to see precisely how the program is using the file.
The operating system will automatically close any open file descriptors when your process terminates.
File data stored in memory (e.g. variables, Python buffers) will be lost. Data buffered in the operating system may be flushed to disk when the file is implicitly closed (checking the exact semantics of in-kernel dirty-buffers here would be educational, though you should not rely on it).
Your variables cease to exist when your process terminates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With