2015-11-02 73 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