File handling with functions? - python

So I got this code that is supposed to sort a dictionary within a json file alphabetically by key:
import json
def values(infile,outfile):
with open(infile):
data=json.load(infile)
data=sorted(data)
with open(outfile,"w"):
json.dump(outfile,data)
values("values.json","values_out.json")
And when I run it I get this error:
AttributeError: 'str' object has no attribute 'read'
I'm pretty sure I messed something up when I made the function but I don't know what.
EDIT: This is what the json file contains:
{"two": 2,"one": 1,"three": 3}

You are using the strings infile and outfile in your json calls, you need to use the file description instance, that you get using as keyword
def values(infile,outfile):
with open(infile) as fic_in:
data = json.load(fic_in)
data = sorted(data)
with open(outfile,"w") as fic_out:
json.dump(data, fic_out)
You can group, with statements
def values(infile, outfile):
with open(infile) as fic_in, open(outfile, "w") as fic_out:
json.dump(sorted(json.load(fic_in)), fic_out)

You forgot to assign the file you opened to a variable. In your current code you open a file, but then try to load the filename rather than the actual file. This code should run because you assign the file object reference to my_file.
import json
def values(infile,outfile):
with open(infile) as my_file:
data=json.load(my_file)
data=sorted(data)
with open(outfile,"w"):
json.dump(outfile,data)
values("values.json","values_out.json")

Related

update the .json file key in python

Json file example = {"process":[{"id":0,"path":"xyz"}, {"id":1,"path":"abc"}]}
with open(process_details.json,"r") as jsonfile:
write_data= json.load(jsonfile)
for processdetails in write_data['process']:
Path = function_to_retreive_path(processdetails['id'])
Write_data[processdetails]['path'] = Path
with open("process_details.json","w") as outfile:
json.dump(write_data,outfile)
As I'm trying to update the path for each process I'm able to retrieve the path but I'm unable to update it in process_details.json file. Getting the following error as unhashable type:'dict'
Can anyone advise me on this issue
Try this:
import json
def function_to_retreive_path (id):
return str (id) + "_updated"
with open("process_details.json","r") as f:
write_data = json.load(f)
for processdetails in write_data['process']:
# debug
print (processdetails)
print (processdetails['id'])
print (processdetails['path'])
# change value
path = function_to_retreive_path (processdetails['id'])
processdetails['path'] = path
# debug
print (processdetails['path'])
with open("process_details.json","w") as outfile:
json.dump(write_data,outfile)
Anyway, your error is caused by a typo. You are using Write_data with a capital W, so Python thinks, I don't know this variable, so it is no dictionary and thus not hashable.
I can't really answer because there are some missing functions in your code so I can't run it, but the error you are facing generally means that you are using a dictionary as a key in an other dictionary.

save json to file, load it and turn it back to object

I'm currently building an application in python where I have a class Corpus. I would like to convert this class to a json format and save it to a json file. Then load the file and finally turn back the json to its Class Corpus.
In order to do that I use the library jsonpickle. The problem is when I load the json, the type is a dictionary and jsonpickle.decode wants a string. I tried to convert the dictionary to a string but its not working.
I hope someone will be able to help me.
Here is my code of my class "Json" (to save and load my Corpus)"
import json, jsonpickle
class Json:
def __init__(self):
self.corpus = {}
def saveCorpus(self,corpus):
jsonCorpus = jsonpickle.encode(corpus,indent=4,make_refs=False)
with open('json_data.json', 'w') as outfile:
outfile.write(jsonCorpus)
def loadCorpus(self):
with open('json_data.json', 'r') as f:
self.corpus = json.load(f)
def getCorpus(self):
return self.corpus
error :
TypeError: the JSON object must be str, bytes or bytearray, not dict
I found the problem.
The issue was the way I was saving my json to a file.
Here is the solution:
def saveCorpus(self,corpus):
jsonCorpus = jsonpickle.encode(corpus,indent=4,make_refs=False)
with open('json_data.json', 'w') as outfile:
json.dump(jsonCorpus, outfile)

How to format JSON style text using python?

I wrote a program to convert KML to GeoJSON. But, when I look at the output files, they are written without whitespace, making them very hard to read.
I tried to use the json module like so:
file = json.load("<filename>")
But it returned the following:
File "/usr/lib/python3.6/json/__init__.py", line 296, in load
return loads(fp.read())
AttributeError: 'str' has no attribute 'read'
load takes a file object, not a file name.
with open("filename") as fh:
d = json.load(fh)
Once you've parsed it, you can dump it again, but formatted a bit more nicely
with open("formatted-filename.json", "w") as fh:
json.dump(d, fh, indent=4)

Python json to CSV

I am trying to convert a json data set file into csv. I am really new to python, and have been looking on the forums and cannot seem to resolve my issues. I have attached the json data url link in below along with my code. Thanks in advance!
https://data.ny.gov/api/views/nqur-w4p7/rows.json?accessType=DOWNLOAD
import json
import csv
inputFile = ("rows.json?accessType=DOWNLOAD", "r")
data = json.load(inputFile)
with open("Data.csv","wb") as csvfile:
csv_writer = csv.DictWriter(csvfile,delimiter=",", fieldnames=["data", "new_york_state_average_gal", "albany_average_gal", "binghamton_average_gal", "bu\
ffalo_average_gal", "nassau_average_gal", "new_york_city_average_gal", "rochester_average_gal", "utica_average_gal"])
csv_writer.writerheader()
csv_writer.writerows(data)
Here is the error I am getting:
File "ChangeDataType.py", line 5, in <module>
data = json.load(inputFile)
File "/usr/lib64/python3.4/json/__init__.py", line 265, in load
return loads(fp.read(),
AttributeError: 'tuple' object has no attribute 'read'
Your error happens because you made a tuple:
inputFile = ("rows.json?accessType=DOWNLOAD", "r")
And you're trying to use json.load in that tuple. Since json.load works only on files, you need to call the open function:
inputFile = open("rows.json?accessType=DOWNLOAD", "r")
The "r" part indicates you're opening the file for reading.

Reading data into Python

I have made a save file using
def Save():
savefile = open('save.txt','w')
savefile.write(str(currentLocation)+'\n')
savefile.close()
print("GAME SAVED!", file=sys.stderr)
which works fine but when I go to load it using...
def Load():
savefile = open('save.txt', 'r')
for line in savefile:
currentLocation.append(currentLocation)
savefile.close()
I get an error called :
AttributeError: 'int' object has no attribute 'append'.
Any reason you can think of why this doesn't work?
You are trying to append to a non-list type object:
currentLocation is not a list
If your file only contains one line (with the number to load), then you can read the file and strip the contents to get the number without new lines, spaces, etc.
def Load():
with open('save.txt', 'r') as loadfile:
currentLocation = int(loadfile.read().strip())
The above with statement will automatically close the file after the nested block of code.
There is also int casting to convert the read number from string to int.

Categories