This forum is now read-only. Please use our new forums at discuss.codecademy.com.

How to use APIs with Python Forum

View Course » View Exercise

1770 points
55c11f9ad3292f956d0004c5_375137961
Submitted by
kouty
almost 2 years ago

14/20 "Parsing JSON" the Codecademy code has a self error? HELP!

    import json
from pprint import pprint

f = open('pets.txt', 'r')
pets = json.loads(f.read())
f.close()

pprint(pets)

Traceback (most recent call last):
File "python", line 4, in
IOError: [Errno 2] No such file or directory: 'pets.txt'


0 votes

permalink

It worked fine for me, not sure what's going on. Try refreshing your browser.

If it still doesn't work, try running this script and see if the file exists at all.

import os
rootdir = "."
found_file = False
print("Trying to locate file: ")
for dirname, subdirList, fileList in os.walk(rootdir):
    for fname in fileList:
        if fname == "pets.txt":
            file_path = os.path.abspath(fname)
            found_file = True
            break
    if found_file:
        break

if found_file:
    print("Path to pets.txt: " + file_path)
else:
    print("Sorry, file does not exist.')

Basically, the script uses the built in os module to parse through directories, starting with your CWD(Current Working Directory.) If the file pets.txt is found, the path to file is stored and printed out, and just replace the text "pets.txt" in the open() function with the path to that file. If no file is found at all, then just print out the following explicitly:

{u'pets': [{u'name': u'Jeffrey', u'species': u'Giraffe'},
       {u'name': u'Gustav', u'species': u'Dog'},
       {u'name': u'Gregory', u'species': u'Duck'}]}    

848 points
252f630586b97efb5f56a6b9ea92d511?s=140&d=retro
Submitted by
DarkxCoder
almost 2 years ago


0 votes

permalink

@darkxCoder
I followed your code:
import os
rootdir = "."
foundfile = False
print("Trying to locate file: ")
for dirname, subdirList, fileList in os.walk(rootdir):
for fname in fileList:
if fname == "pets.txt":
file
path = os.path.abspath(fname)
foundfile = True
break
if found
file:
break

if found_file:
    print("Path to pets.txt: " + file_path)
else:
    print("Sorry, file does not exist.")
-----------------------------------------------------

IT'S GOOOOOOOOOOOOOOOOD?
Trying to locate file:
Path to pets.txt: /home/run1670/pets.txt
None

1770 points
55c11f9ad3292f956d0004c5_375137961
Submitted by
kouty
almost 2 years ago

1 Comment

252f630586b97efb5f56a6b9ea92d511?s=140&d=retro DarkxCoder almost 2 years ago

Glad that it worked!