简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM