2015-11-02 75 views
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. 
''' 

因此,對於這個功能,我會簡單地只是這樣做:保存文件,或者如果它覆蓋掉

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

什麼我不理解的是返回真/假,壓延是否保存。如果我創建的文本文件,並只是檢查它是否存在應該不夠?

+0

那麼,相同的日曆? http://stackoverflow.com/q/33459213/5299236 –

+0

而關於你的問題,函數需要覆蓋它,如果它已經存在*,所以只需打開(calendar.txt,'w')'?如果文件中有文本,'w'模式將清除文件的文本。 –

+0

我不是很瞭解你說的w模式的部分 – JerryMichaels

回答

0

您可以閱讀蟒蛇網站首頁的文檔: os.path.exists

的存在(路徑)函數只是檢查是否路徑參數指的是現有的路徑或沒有。在你的情況下,如果存在calendar.txt,則返回True,否則返回False。 exists()函數在返回False時不會創建新文件。

所以你的代碼是確定的。

1

我想你可以簡單地做到這一點。

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