Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I don't close a txt file

I'm about to write a program for a racecar, that creates a txt and continuously adds new lines to it. Unfortunately I can't close the file, because when the car shuts off the raspberry (which the program is running on) gets also shut down. So I have no chance of closing the txt.

Is this a problem?

like image 356
Nglhrdtptrck Avatar asked May 17 '14 16:05

Nglhrdtptrck


People also ask

What happens if you don't close a file after writing to it?

In a large program, which runs on long after you have finished reading/writing to the file, not closing it means that your program is still holding the resource. This means that other processes cannot acquire that file until your program terminates (which may not be what you wish for).

Is it compulsory to close a file?

Not closing a file will result in unnecessary resources being taken from the system (File Descriptors on Unix and Handles on windows). Especially when a bug happens in some sort of loop or a system is never turned off, this gets important.

Why closing a file is necessary in file?

You've learned why it's important to close files in Python. Because files are limited resources managed by the operating system, making sure files are closed after use will protect against hard-to-debug issues like running out of file handles or experiencing corrupted data.

Is it mandatory to close a text file which is opened?

Yes, it is necessary to close the file when you need it for reading again. Only if you close a file, the changes that you have made will be reflected because only when closing, the updated contents will be flushed to the disk from memory. So, when you open it again for reading, you will find the updated contents.


1 Answers

Yes and no. Data is buffered at different places in the process of writing: the file object of python, the underlying C-functions, the operating system, the disk controller. Even closing the file, does not guarantee, that all these buffers are written physically. Only the first two levels are forced to write their buffers to the next level. The same can be done by flushing the filehandle without closing it. As long as the power-off can occur anytime, you have to deal with the fact, that some data is lost or partially written. Closing a file is important to give free limited resources of the operating system, but this is no concern in your setup.

like image 112
Daniel Avatar answered Sep 25 '22 02:09

Daniel