This question already has answers here:
How to append data to a json file?
(11 answers)
Closed 3 years ago.
I have a .json file which I would like to append data to. But only if this string is not in the .json file already.
JSON File:
[{"filename":"file1"}, {"filename":"file2"}, {"filename":"file3"}]
End result JSON File:
[{"filename":"file1"}, {"filename":"file2"}, {"filename":"file3"}, {"filename":"file4"}]
I currently have this:
with open('gdrivefiles.json', 'r') as f:
filenameslist = json.load(f) #Loads the .json file into a string (If I'm right)
for distro in filenameslist:
filenames = distro["filename"] #Gets a list of all the filenames
if name in filenames:
print("yes") #If name is in the list of filenames print 'yes'
else:
print("no") #If name is in the list of filenames print 'no'
(This code is put in a for-loop, so it will run this code for every new value of name)
How would I add name ({"filename":"name"}) in the json file if it is not in it already?
This code should do what you want:
import json
new_file = {"filename":"name"}
data = json.load(open("data.json"))
if not any([new_file['filename'] == x['filename'] for x in data]):
data.append(new_file)
json.dump(data, open("data.json","w"))
You just need to create the data structure when writing back:
import json
name = "file4"
with open('gdrivefiles.json', 'r') as f:
filenameslist = json.load(f)
filenames = [distro["filename"] for distro in filenameslist]
if name in filenames:
print("yes") #If name is in the list of filenames print 'yes'
else:
print("no") #If name is in the list of filenames print 'no'
filenames.append(name)
# write filenames back to file as list of dicts!
with open('gdrivefiles.json', 'w') as f:
f.write(json.dumps([{'filename': name} for name in filenames]))
import json
new_object = {"filename":"file5"}
with open('data.json') as json_file:
data = json.load(json_file)
if new_object not in data:
data.append(new_object)
json_file.close()
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
outfile.close()
Related
How to dump data into Json file
*as can see in the below python code I am trying the dump data in Json file so but I am struggling to do it in python code *
import time
import json
import os
def long_function(name):
cache_path = 'cache.json'
if not os.path.isfile(cache_path):
with open(cache_path, 't') as json_file:
cache_file_data = [name]
jsondump(cache_file_data, json_file)
else:
with open(cache_path, 'r') as json_file:
cache_file_data = json.load(json_file)
if name in cache_file_data:
print("Name already exist")
return name
else:
cache_file_data.append(name)
for e in range(5):
time.sleep(1)
print(e+1)
with open(cache_path, 'w') as json_file:
jsondump(cache_file_data, json_file)
print("New Name added in cache")
return name
print(long_function('nitu'))
so please resolve my problem......please help me
import json
# JSON data:
x = '{ "organization":"New_holn",
"city":"Noida",
"country":"India"}'
# python object to be appended
y = {"pin":117845}
# parsing JSON string:
z = json.loads(x)
# appending the data
z.update(y)
# the result is a JSON string:
print(json.dumps(z))
This is nothing but follow this pattern and your so your code error is ..you are not defined file mode correctly in if condition
with open (cache_path. "t") as json_file:
Instead of
with open (cache_path. "w") as json_file:
And second thing is you are not doing dump data
In a simple Telegram bot with Telebot I have a dictionary in json format (parole.json). I'm trying a function that allows me to delete an entry (key value pair) from the dictionary and I used this code example found right on this forum:
import json
with open("parole.json", "r") as json_file:
Dizio = json.load(json_file)
#bot.message_handler(commands=['cut'])
def removeKey(message):
parola = extract_arg(message.text.lower())
res = Dizio.get(message.text.lower(), parola)
trova = str(parola)
with open("parole.json", "r") as f:
data = json.load(f)
if trova in data:
del data[trova]
with open("parole.json", "w") as f:
json.dump(data, f)
Have you read this question? It's basically the same question and the answer is already given.
You need to iterate over the keys by using a for loop that checks if the input == ['key']['value']
Also, your indenting is incorrect in your removekey(message) function:
def removeKey(message):
parola = extract_arg(message.text.lower())
res = Dizio.get(message.text.lower(), parola)
trova = str(parola)
with open("parole.json", "r") as f:
data = json.load(f)
if trova in data:
del data[trova]
with open("parole.json", "w") as f:
json.dump(data, f)
Edit: I see that the indentation was edited just now
if trova in data:
del data[trova]
Calling dict.__del__ removes the key/value pair, so if your file is unchanged it's because the flow never enters the if statement.
Maybe it would work with
if trova in data.keys():
but I'm not sure if it makes any difference.
This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 2 years ago.
the idea is to write a python code reading data from a text file indicated below.
https://www.minorplanetcenter.net/iau/MPCORB/CometEls.txt
Further on, I would like to filter comet-data like name magnitude etc. etc.
Right now my problem is getting data output.
My code is:
import os.path
word_dict = {}
scriptpath = os.path.dirname(__file__)
filename = os.path.join(scriptpath, 'CometEls.txt','r')
for line in filename:
line = line.strip()
relation = line.split(' ')
word_dict[relation[0]] = relation[0:20]
while True:
word = input('Comet name : ')
if word in word_dict:
print ('Comets in list :' , word_dict[word])
print(filename) #show file location
else:
print( 'No comet data!')
print(word_dict) #show data from dictionary
As you can see data in my dictionary isn't the comet-data.
It should be
Typing in "a"
Theoretically the code works, the problem is creating the dictionary?
Maybe I'm completely wrong, but it doesn't work neither with tuples or lists, or it's better to copy data into a .csv file?
Best regards
You saved the file path to the filename variable, but did not open the file for reading. You should open file, and then read it:
import os.path
word_dict = {}
scriptpath = os.path.dirname(__file__)
file_path = os.path.join(scriptpath, 'CometEls.txt')
with open(file_path, 'r') as commet_file:
for line in commet_file:
line = line.strip()
relation = line.split(' ')
word_dict[relation[0]] = relation[0:20]
while True:
word = input('Comet name : ')
if word in word_dict:
print ('Comets in list :' , word_dict[word])
print(file_path)
else:
print('No comet data!')
print(word_dict) #show data from dictionary
Also, your example has wrong margins near in while block, please check it.
I'm attempting to convert yelps data set that is in JSON to a csv format. The new csv file that is created is empty.
I've tried different ways to iterate through the JSON but they all give me a zero bytes file.
The json file looks like this:
{"business_id":"1SWheh84yJXfytovILXOAQ","name":"Arizona Biltmore Golf Club","address":"2818 E Camino Acequia Drive","city":"Phoenix","state":"AZ","postal_code":"85016","latitude":33.5221425,"longitude":-112.0184807,"stars":3.0,"review_count":5,"is_open":0,"attributes":{"GoodForKids":"False"},"categories":"Golf, Active Life","hours":null}
import json
import csv
infile = open("business.json","r")
outfile = open("business2.csv","w")
data = json.load(infile)
infile.close()
out = csv.writer(outfile)
out.writerow(data[0].keys())
for row in data:
out.writerow(row.values())
I get an "extra data" message when the code runs. The new business2 csv file is empty and the size is zero bytes.
if you JSON has only one row.. then try this
infile = open("business.json","r")
outfile = open("business2.csv","w")
data = json.load(infile)
infile.close()
out = csv.writer(outfile)
#print(data.keys())
out.writerow(data.keys())
out.writerow(data.values())
Hi Please try the below code, by using with command the file access will automatically get closed when the control moves out of scope of with
infile = open("business.json","r")
outfile = open("business2.csv","w")
data = json.load(infile)
infile.close()
headers = list(data.keys())
values = list(data.values())
with open("business2.csv","w") as outfile:
out = csv.writer(outfile)
out.writerow(headers)
out.writerow(values)
You need to use with to close file.
import json
import csv
infile = open("business.json","r")
data = json.load(infile)
infile.close()
with open("business2.csv","w") as outfile:
out = csv.writer(outfile)
out.writerow(list(data.keys()))
out.writerow(list(data.values()))
I wanted to edit a csv file which reads the value from one of my another json file in python 2.7
my csv is : a.csv
a,b,c,d
,10,12,14
,11,14,15
my json file is a.json
{"a":20}
i want my where the column 'a' will try to match in json file. if their is a match. it should copy that value from json and paste it to my csv file and the final output of my csv file should be looks like this.
a,b,c,d
20,10,12,14
20,11,14,15
Till now I what I have tried is
fileCSV = open('a.csv', 'a')
fileJSON = open('a.json', 'r')
jsonData = fileJSON.json()
for k in range(jsonData):
for i in csvRow:
for j in jsonData.keys():
if i == j:
if self.count == 0:
self.data = jsonData[j]
self.count = 1
else:
self.data = self.data + "," + jsonData[j]
self.count = 0
fileCSV.write(self.data)
fileCSV.write("\n")
k += 1
fileCSV.close()
print("File created successfully")
I will be really thankful if anyone can help me for this.
please ignore any syntactical and indentation error.
Thank You.
Some basic string parsing will get you here.. I wrote a script which works for the simple scenario which you refer to.
check if this solves your problem:
import json
from collections import OrderedDict
def list_to_csv(listdat):
csv = ""
for val in listdat:
csv = csv+","+str(val)
return csv[1:]
lines = []
csvfile = "csvfile.csv"
outcsvfile = "outcsvfile.csv"
jsonfile = "jsonfile.json"
with open(csvfile, encoding='UTF-8') as a_file:
for line in a_file:
lines.append(line.strip())
columns = lines[0].split(",")
data = lines[1:]
whole_data = []
for row in data:
fields = row.split(",")
i = 0
rowData = OrderedDict()
for column in columns:
rowData[columns[i]] = fields[i]
i += 1
whole_data.append(rowData)
with open(jsonfile) as json_file:
jsondata = json.load(json_file)
keys = list(jsondata.keys())
for key in keys:
value = jsondata[key]
for each_row in whole_data:
each_row[key] = value
with open(outcsvfile, mode='w', encoding='UTF-8') as b_file:
b_file.write(list_to_csv(columns)+'\n')
for row_data in whole_data:
row_list = []
for ecolumn in columns:
row_list.append(row_data.get(ecolumn))
b_file.write(list_to_csv(row_list)+'\n')
CSV output is not written to the source file but to a different file.
The output file is also always truncated and written, hence the 'w' mode.
I would recommend using csv.DictReader and csv.DictWriter classes which will read into and out of python dicts. This would make it easier to modify the dict values that you read in from the JSON file.