4

Here's my code:

import json    
with open("json.items") as json_file:
        json_data = json.load(json_file)

It works fine when I move the json file into the same directory. However, I'm trying to get the json file from a different directory. How would I do that? This is what I have tried and its not working:

with open("/lowerfolder/json.items") as json_file:

Any help? Thanks

5
  • 3
    Depending on your platform, starting a path with / means absolute path from the root Commented Jan 23, 2014 at 1:23
  • 2
    Meaning a relative path should be open("lowerfolder/json.items") without the / Commented Jan 23, 2014 at 1:25
  • 1
    What @mhlester said, or alternatively open('./lowerfolder/json.items'), or use a full absolute path (e.g. open('/home/strikepricer/files/lowerfolder/json.items')). Commented Jan 23, 2014 at 1:26
  • What platform are you running the code? Mac, linux, or windows? Commented Jan 23, 2014 at 1:26
  • actually it worked! "lowerfolder/items.json" no / needed. Commented Jan 23, 2014 at 1:34

1 Answer 1

8

Depending on your platform, starting a path with / means absolute path from the root

Meaning a relative path should be open("lowerfolder/json.items") without the /

Sign up to request clarification or add additional context in comments.

3 Comments

You should probably move the first paragraph (about whether this is good form) to a comment on your answer, or at the very least to a parenthetical at the end of the answer, instead of being at the very top. But otherwise, there's nothing wrong with your form. Most importantly, it's a good answer that will be useful to anyone with this problem, and you even expanded it from your original comment. And you're not trying to steal anyone else's credit or game the system. So… what could be wrong with it?
Thanks @abarnert. I've never done it before so I thought I'd check. It didn't seem to benefit anyone else; I hadn't thought of visitors from the future (hi future people!)
Always remember Guido's time machine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.