0
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?

JerryMichaels
  • 109
  • 1
  • 4
  • 9
  • Well, the same calendars? http://stackoverflow.com/q/33459213/5299236 – Remi Guan Nov 02 '15 at 02:09
  • And about your question, the function need *overwriting it if it already exists*, so just `open(calendar.txt, 'w')`? `w` mode will clear the text of a file if there is text in that file. – Remi Guan Nov 02 '15 at 02:12
  • I'm not quite understanding the part about the w mode you said – JerryMichaels Nov 02 '15 at 02:16
  • Okay, so possible duplicate of [Why truncate when we open a file in 'w' mode in python](http://stackoverflow.com/questions/4562100/why-truncate-when-we-open-a-file-in-w-mode-in-python) – Remi Guan Nov 02 '15 at 02:17

2 Answers2

2

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
sunhs
  • 391
  • 1
  • 6
0

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.

Vuong Hoang
  • 149
  • 8