【发布时间】:2014-11-02 21:41:19
【问题描述】:
我有以下 Python 代码:
class Server(object):
def __init__(self, options):
self.data_file = '/etc/my_module/resources.json'
# Triggered when new data is received
def write(self, data):
try:
f = open(self.data_file, 'w')
json.dump(data, f)
except Exception, e:
print e
finally:
f.close()
如果文件/etc/my_module/resources.json 不存在,那么当我调用write 方法时会收到一条错误消息:
[Errno 2] No such file or directory: '/etc/my_module/resources.json'
如果我手动创建文件并再次调用 write 方法,那么一切正常,json 被写入文件。
我正在使用 sudo:sudo python my_module.py 运行我的应用程序,并且我已将我的用户 (vagrant) 添加到 /etc/sudoers。
所以如果文件不存在,python 不会创建文件,理由是它没有写入 /etc 的权限,但如果文件存在,它会很高兴地写入文件。这是为什么呢?
【问题讨论】:
标签: python