Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: what happens to opened file if i quit before it is closed?

Tags:

python

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?

like image 260
Alex Gordon Avatar asked Aug 04 '10 16:08

Alex Gordon


People also ask

What happens if you leave a file open in Python?

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.

Do you have to close file after open Python?

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.

What happens if you leave a program without closing open write files Python?

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.

Do I need to close file after with open?

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.


1 Answers

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.

like image 150
Noah Watkins Avatar answered Sep 30 '22 19:09

Noah Watkins