尝试时出现意外结果,打开

时间:2017-03-31 09:05:31

标签: python python-2.7 python-3.x

无法想出这一个,网上也似乎没有任何信息。尝试使用Python 2和3。

def load_settings():
    try:
        with open('settings.txt', 'r') as f:
            return f.read()
    except FileNotFoundError:
        with open('settings.txt', 'w') as f:
            f.write('default_settings')
        load_settings()

我希望上面的函数返回'default_settings',因为settings.txt尚不存在。而是返回None

2 个答案:

答案 0 :(得分:0)

将您的最后一行更改为

return load_settings()

否则,您可以调用您的函数,但不要返回其值。

答案 1 :(得分:-1)

将您的代码更改为此

def load_settings():
    try:
        with open('settings.txt', 'r') as f:
            return f.read()
    except FileNotFoundError:
        with open('settings.txt', 'w') as f:
            f.write('default_settings')
        return load_settings()