0

I'm really new to Python, and I am trying to create a script that appends JSON to the end of a pre-existing JSON file. The way my server runs is that it only executes Python folders in the cgi-bin folder (public_html/cgi-bin).

I have the JSON file and the Python script file in the same directory and attempt to alter it with the following code:

#!/usr/bin/env python

import cgi
import json

new_data = {"2": {"title": "what", "date": "tomorrow"}}

print("Content-type: application/json\n\r")

with open("jobs.json") as file:
    data = json.load(file)

data.update(new_data)

with open('jobs.json', 'w') as file:
    json.dump(data, file)

But when I load that page nothing happens, jobs.json stays the same.

I talked to my server provider and they said that JSON files in the cgi-bin are considered just being in public_html (if I access them there in my address bar, it finds it fine, whereas it doesn't in the cgi-bin directory). Then how do I access users.json if it's apparently back at public_html?

The path to the Python file is /public_html/ooproject/two.py and jobs.json is in that same directory.

Doug Smith
  • 29,668
  • 57
  • 204
  • 388

1 Answers1

1

You may try __file__ variable. It contains name of your script and combined with os.path may give what you want. Try this:

#!/usr/bin/env python

import cgi
import json
import os.path

new_data = {"2": {"title": "what", "date": "tomorrow"}}

print("Content-type: application/json\n\r")

script_dir = os.path.dirname(os.path.abspath(__file__))
fname = os.path.join(script_dir, 'jobs.json')

with open(fname) as f:
    data = json.load(f)

data.update(new_data)

with open(fname, 'w') as f:
    json.dump(data, f)

Note: avoid using file for variable name, because it's a name of Python type.

Tupteq
  • 2,986
  • 1
  • 21
  • 30
  • This works great, but why exactly does it put it in random places? If I put -2 instead of 2, it adds it to the end, and then if I change it to 17, it adds it before -2. And if I have an empty file, it won't add anything. – Doug Smith Nov 26 '13 at 18:36
  • Dictionary in Python isn't ordered, which means that if you iterate over it's keys you may receive them in random order. If you really want to sort keys in particular way, use [OrderedDict](http://docs.python.org/2/library/collections.html#collections.OrderedDict), take a look at [this question's solution](http://stackoverflow.com/questions/6921699/can-i-get-json-to-load-into-an-ordereddict-in-python). If consistent order of keys is enough, you may just use `sort_keys` parameter: `json.dump(data, f, sort_keys=True)`. – Tupteq Dec 08 '13 at 15:28