Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I exit without saving a file in Python

Tags:

python

I am new to python and have until now written only a few programs to help with my job (I'm a sysadmin). I am writing this script now which will write the output of a MySQL query to a file. While in-between looping, I want to check for an extra condition and if the condition does not match, I want to close the file that I am writing to without saving what it has already written to the file. Like 'exit without saving'. I wrote this simple code to see if not closing the file with a close() will exit without saving, but it is creating the file with the content after I run and exit this code. So, is there a legal way in Python to exit a file without saving?

#/usr/bin/python
fo=open('tempfile.txt','a')
fo.write('This content\n')

P.S:- Python version is 2.4.3 (sorry, cannot upgrade)

like image 974
Sreeraj Avatar asked Apr 06 '26 11:04

Sreeraj


1 Answers

There is no such concept in programming.

For the vast majority of the programming languages out there, the write command will attempt to put data directly in the file. This may or may not occur instantly for various reasons so many languages also introduce the concept of flush which will guarantee that your data is written to the file

What you want to do instead is to write all your data to a huge buffer (a string) then conditionally write or skip writing to the file.

like image 160
Eric Avatar answered Apr 09 '26 02:04

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!