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

时间:2015-11-02 02:07:22

标签: python python-3.x

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()

我不理解的是返回真/假,是否保存了日历。如果我创建了文本文件,只需检查它是否存在就不够了吗?

2 个答案:

答案 0 :(得分:1)

我认为你可以做到这一点。

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

答案 1 :(得分:0)

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

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

所以你的代码没问题。