0

I've got the following Python code:

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

If the file /etc/my_module/resources.json does not exist then I get an error message when I call the write method:

[Errno 2] No such file or directory: '/etc/my_module/resources.json'

If I create the file manually and call the write method again, then everything works and the json is written to the file.

I'm running my application with sudo: sudo python my_module.py, and I've added my user (vagrant) to /etc/sudoers.

So python won't create the file if it doesn't exist, on the grounds that it doesn't have permission to write to /etc, but it will happily write to the file if it does exist. Why is this?

stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189

2 Answers2

4

Change

f = open(self.data_file, 'w')

To

f = open(self.data_file, 'w+')
2

Creating a new file involves writing a new file entry to the directory which requires write permissions on the directory. Modifying an existing file bypasses this.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358