保存或覆盖文件(如果存在)

2024-06-26 14:43:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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.
'''

对于这个函数,我只需要做这个:

^{pr2}$

我不明白的是返回的是真是假,日历是否被保存了。如果我创建了文本文件并简单地检查它是否存在,这还不够吗?在


Tags: thetesttxtgodateiswithit
2条回答

我想你可以这么做。在

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

您可以阅读python主页的文档: os.path.exists

exists(path)函数只检查path参数是否引用现有路径。在您的例子中,如果calendar.txt存在,则返回True,否则返回False。exists()函数返回False时不会生成新文件。在

所以你的代码没问题。在

相关问题 更多 >