user2066480
user2066480

Reputation: 1365

Don't save empty file

I create a new text file with f = open('file.txt', 'w'). Then, as I go about to get stuff to write on it, there is a problem and I need to exit without actually writing anything.

However, the file is still created, but empty. Is there a way to keep the file from being saved in case nothing is going to be written on it, or do I have to explicitly delete it in case something goes wrong?

Upvotes: 1

Views: 1172

Answers (2)

Farmer Joe
Farmer Joe

Reputation: 6070

You could simply prepare the information for writing first and only perform the saving and such if it makes it through preparation without a hitch.

info_to_write = ""
try:

    info_to_write += "something!"
    # etc...

    if something_went_wrong:
        raise Exception
    with open("file.txt","w") as f:
        f.write(info_to_write)
catch:
    print "Nothing written, no file created"

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54173

You can use atexit to simulate this behavior, but there's probably a Better Way out there somewhere.

import atexit

def safety_trigger():
    try:
        os.remove(FILENAME)
    except FileNotFoundError:
        pass

atexit.register(safety_trigger)

with open(FILENAME,'w') as f:
    # do your
    # file operations
    atexit.unregister(safety_trigger)

This way when your script starts, you set it to automatically delete FILENAME when it ends. Once you're done writing to the file, you tell your script NOT to automatically delete FILENAME when it ends.

Upvotes: 1

Related Questions