JerryMichaels
JerryMichaels

Reputation: 109

Saving a file or overwriting it if it exists

def save_calendar(calendar):
'''
Save calendar to 'calendar.txt', overwriting it if it already exists.

The format of calendar.txt is the following:

date_1:description_1\tdescription_2\t...\tdescription_n\n
date_2:description_1\tdescription_2\t...\tdescription_n\n
date_3:description_1\tdescription_2\t...\tdescription_n\n
date_4:description_1\tdescription_2\t...\tdescription_n\n
date_5:description_1\tdescription_2\t...\tdescription_n\n

Example: The following calendar...

    2015-10-20:
        0: Python 
    2015-11-01:
        0: CSC test 2
        1: go out with friends after test

appears in calendar.txt as ...

2015-10-20:Python 
2015-11-01:CSC test 2    go out with friends after test

                        ^^^^ This is a \t, (tab) character.


:param calendar:
:return: True/False, depending on whether the calendar was saved.
'''

So for this function would i simply just do this:

if not os.path.exists(calendar.txt):
    file(calendar.txt, 'w').close()

What i'm not understanding is the return true/false, whether the calender was saved. If i created the text file and simply check if it exists shouldn't that be enough?

Upvotes: 0

Views: 5147

Answers (2)

sunhs
sunhs

Reputation: 401

I think you can simply do this.

with open('calendar.txt', 'w') as cal: # file would be created if not exists
    try:
        cal.write(yourdata)
    except:
        return False
return True

Upvotes: 2

Vuong Hoang
Vuong Hoang

Reputation: 149

You can read the document of python homepage: os.path.exists

The exists(path) function just check if the path argument refers to an existing path or not. In your case, return True if calendar.txt is exist, and return False otherwise. The exists() function don't make a new file when it return False.

So your code are OK.

Upvotes: 0

Related Questions