python program to write to json from input - python

I made a program in python3 that writes to json upon input from user. Program is running but includes slashes
i want it to be
Output:(written to a file sample.json)
{
"api" : api_key=4ewrs5798hoknlkmnnmhbvjgfd7"
}
But instead i get
Output:(written to a file sample.json)
{\"api\":\"api_key=4ewrs5798hoknlkmnnmhbvjgfd7\"}"
Backslash appears at every (") also indents are missing even if declared or not
import json
k1 = input("enter key")
k2 ='{"api" : ""api_key='+k1+'"}'
with open("sample.json", "w") as outfile:
json.dump(k2, outfile, indent=4)
print("success")

The problem has to do with the quotations you are using in k2. A better way of doing this is to use dicts.
import json
k2 = {}
k2['api'] = "api_key=" + input("enter key")
with open("sample.json", "w") as outfile:
json.dump(k2, outfile, indent=4)
print("success")

Related

JSON file rewrites data after I re-run the program

I wanted to make a program that tracks the progress of our competition. I made a library containing our names as the key, and our wins as the value. I then made a JSON file to save the progress. But for some reason, when I re-run the program, it goes back to it's initial values and adds the new one; as if it was the first time I used the program.
Here is my code:
import os, json, sys
Numbers = {
"Peter" : 1,
"Drew" : 1,
}
def q1():
New_numbers = {}
q = input("Name? ")
if q not in Numbers:
Numbers[q] =1
with open("list.json", "w") as f:
json.dump(Numbers, f)
f.close()
with open("list.json", "r") as f:
New_numbers = json.load(f)
for key,value in New_numbers.items():
print(key, ":", value)
elif q in Numbers:
Numbers[q] += 1
with open("list.json", "w") as f:
json.dump(Numbers, f)
f.close()
with open("list.json", "r") as f:
New_numbers = json.load(f)
for key,value in New_numbers.items():
print(key, ":", value)
q1()
The first use, it works perfectly. However, as I've mentioned before, when I use it again, it loads the initial library; not the JSON file.

how do I add a string to a json value in python 3

So I'm trying to setup json so i can store data in-between user sessions I like a name but i don't know how to add or change a specific value in an external json file like for example {"name": ""} how do i fill that "" for the json file using python?
I have already tried to use dumps and all the tutorials use dumps
the json in another file
{
"human_name": "",
"oracle_name": "",
"human_age": "",
"human_gender": "",
"oracle_gender": ""
}
the python
import json
with open('data.json', '+') as filedata:
data = filedata.read()
used_data = json.loads(data)
if str(used_data(['human_name'])) == "":
print("what is your name")
name = input()
json.dumps(name)
if str(used_data(['oracle_name'])) == "":
print("what is my name")
oracle_name = input()
json.dumps(oracle_name)
print(str(['human_name']))
The expected result is when I print the data it displays input, but when i run it it goes
File "rember.py", line 3, in
with open('data.json', '+') as filedata: ValueError: Must have exactly one of create/read/write/append mode and at most one plus
Try this code.
json.loads loads the entire json string as a python dict object. The values in a dict are changed/added using dict[key] = value. You can't call a dict object to change its value.
The json.dumps method serializes an object to a JSON formatted str. Which you can then write into the same file or a different file based on your requirement.
import json
with open('data.json', 'r') as filedata:
data = filedata.read()
used_data = json.loads(data)
if used_data['human_name'] == "":
print("what is your name")
name = input()
used_data['human_name'] = name
if used_data['oracle_name'] == "":
print("what is my name")
oracle_name = input()
used_data['oracle_name'] = oracle_name
print(used_data)
with open('data.json', 'w') as filewrite:
filewrite.write(json.dumps(used_data, indent=4))
Basically what you need to do is load json file as dictionary, add value, and save it.
import json
with open('./data.json', 'r') as f:
d = json.load(f)
d['human_name'] = 'steve'
d['oracle_name'] = 'maria'
with open('./data.json', 'w') as f:
json.dump(d, f, indent=4)

keep data in the file python

hi guys how are you I hope that well, I'm new using python and I'm doing a program but I dont know how to save the data permanently in a file. I only know how to create the file but i dont know how can i keep the data on the file eventhough the program be closed and when i open it back i be able to add more data and keep it in the file too.I have also tried several methods to upload the file on python but they didnt work for me. Can someone please help me?
This is my code:
file = open ('file.txt','w')
t = input ('name :')
p= input ('last name: ')
c = input ('nickname: ')
file.write('name :')
file.write(t)
file.write(' ')
file.write('last name: ')
file.write(p)
file.write('nickname: ')
file.write(c)
file.close()
with open('archivo.txt','w') as file:
data = load(file)
print(data)
Here is a demonstration of how file writing works, and the difference between w and a. The comments represent the text in the file that is written to the drive at each given point.
f1 = open('appending.txt', 'w')
f1.write('first string\n')
f1.close()
# first string
f2 = open('appending.txt', 'a')
f2.write('second string\n')
f2.close()
# first string
# second string
f3 = open('appending.txt', 'w')
f3.write('third string\n')
f3.close()
# third string
There are three type of File operation mode can happen on file like read, write and append.
Read Mode: In this you only able to read the file like
#content in file.txt "Hi I am Python Developer"
with open('file.txt', 'r') as f:
data = f.read()
print(data)
#output as : Hi I am Python Developer
Write Mode: In this you are able to write information into files, but it will always overwrite the content of the file like for example.
data = input('Enter string to insert into file:')
with open('file.txt', 'w') as f:
f.write(data)
with open('file.txt', 'r') as f:
data = f.read()
print('out_data:', data)
# Output : Enter string to insert into file: Hi, I am developer
# out_data: Hi, I am developer
When you open file for next time and do same write operation, it will overwrite whole information into file.
Append Mode: In this you will able to write into file but the contents is append into this files. Like for example:
data = input('Enter string to insert into file:')
with open('file.txt', 'a') as f:
f.write(data)
with open('file.txt', 'r') as f:
data = f.read()
print('out_data:', data)
# Output : Enter string to insert into file: Hi, I am developer
# out_data: Hi, I am developer
# Now perform same operation:
data = input('Enter string to insert into file:')
with open('file.txt', 'a') as f:
f.write(data)
with open('file.txt', 'r') as f:
data = f.read()
print('out_data:', data)
# Output : Enter string to insert into file: Hi, I am Python developer
# out_data: Hi, I am developer Hi, I am Python Developer

How to encode a pre-existing text file to utf-8 in separate file?

I'm attempting to encode a pre-existing text file and write it in utf-8. I've made a menu in which the user is asked for which text file they would like to encode, but after that I am absolutely lost. I was looking at a previous post and I incorporated that code into my code, however I am unsure of how it works or what I'm doing.
Any help would be greatly appreciated!
import codecs
def getMenuSelection():
print "\n"
print "\t\tWhich of the following files would you like to encode?"
print "\n"
print "\t\t================================================"
print "\t\t1. hamletQuote.txt"
print "\t\t2. RandomQuote.txt"
print "\t\t3. WeWillRockYou.txt"
print "\t\t================================================"
print "\t\tq or Q to quit"
print "\t\t================================================"
print ""
selection = raw_input("\t\t")
return selection
again = True
while (again == True):
choice = getMenuSelection()
if choice.lower() == 1 :
with codecs.open(hamletQuote.txt,'r',encoding='utf8') as f:
text = f.read()
with codecs.open(hamletQuote.txt,'w',encoding='utf8') as f:
f.write(text)
if choice.lower() == 2 :
with codecs.open(RandomQuote.txt,'r',encoding='utf8') as f:
text = f.read()
with codecs.open(RandomQuote.txt,'w',encoding='utf8') as f:
f.write(text)
if choice.lower() == 3 :
with codecs.open(WeWillRockYou.txt,'r',encoding='utf8') as f:
text = f.read()
with codecs.open(WeWillRockYou.txt,'w',encoding='utf8') as f:
f.write(text)
elif choice.lower() == "q":
again = False
Your code will work correctly, though you need to make the filenames strings. Your input filename is also the same as the output filename, so the input file will be overwritten. You can fix this by naming the output file something different:
with codecs.open("hamletQuote.txt",'r',encoding='utf8') as f:
text = f.read()
with codecs.open("hamletQuote2.txt",'w',encoding='utf8') as f:
f.write(text)
If your curious how it works, codecs.open opens an encoded file in the given mode; in this case r which means read mode. w refers to write mode. f refers to the file object which has several methods including read() and write() (which you used).
When you use the with statement it simplifies opening the file. It ensures clean-up is always used. Without the with block, you would have to specify f.close() after you have finished working with the file.
Why don't you use the regular open statement and open the file as binary and write the encoded text to utf-8, you will need to open the file as regular read mode since it's not encoded:
with open("hamletQuote.txt", 'r') as read_file:
text = read_file.read()
with open("hamletQuote.txt", 'wb') as write_file:
write_file.write(text.encode("utf-8"))
But if you insist on using codecs, you can do this:
with codecs.open("hamletQuote.txt", 'r') as read_file:
text = read_file.read()
with codecs.open("hamletQuote.txt", 'wb', encoding="utf-8") as write_file:
write_file.write(text.encode("utf-8"))

Append JSON to file

I am trying to append values to a json file. How can i append the data? I have been trying so many ways but none are working ?
Code:
def all(title,author,body,type):
title = "hello"
author = "njas"
body = "vgbhn"
data = {
"id" : id,
"author": author,
"body" : body,
"title" : title,
"type" : type
}
data_json = json.dumps(data)
#data = ast.literal_eval(data)
#print data_json
if(os.path.isfile("offline_post.json")):
with open('offline_post.json','a') as f:
new = json.loads(f)
new.update(a_dict)
json.dump(new,f)
else:
open('offline_post.json', 'a')
with open('offline_post.json','a') as f:
new = json.loads(f)
new.update(a_dict)
json.dump(new,f)
How can I append data to json file when this function is called?
I suspect you left out that you're getting a TypeError in the blocks where you're trying to write the file. Here's where you're trying to write:
with open('offline_post.json','a') as f:
new = json.loads(f)
new.update(a_dict)
json.dump(new,f)
There's a couple of problems here. First, you're passing a file object to the json.loads command, which expects a string. You probably meant to use json.load.
Second, you're opening the file in append mode, which places the pointer at the end of the file. When you run the json.load, you're not going to get anything because it's reading at the end of the file. You would need to seek to 0 before loading (edit: this would fail anyway, as append mode is not readable).
Third, when you json.dump the new data to the file, it's going to append it to the file in addition to the old data. From the structure, it appears you want to replace the contents of the file (as the new data contains the old data already).
You probably want to use r+ mode, seeking back to the start of the file between the read and write, and truncateing at the end just in case the size of the data structure ever shrinks.
with open('offline_post.json', 'r+') as f:
new = json.load(f)
new.update(a_dict)
f.seek(0)
json.dump(new, f)
f.truncate()
Alternatively, you can open the file twice:
with open('offline_post.json', 'r') as f:
new = json.load(f)
new.update(a_dict)
with open('offline_post.json', 'w') as f:
json.dump(new, f)
This is a different approach, I just wanted to append without reloading all the data. Running on a raspberry pi so want to look after memory. The test code -
import os
json_file_exists = 0
filename = "/home/pi/scratch_pad/test.json"
# remove the last run json data
try:
os.remove(filename)
except OSError:
pass
count = 0
boiler = 90
tower = 78
while count<10:
if json_file_exists==0:
# create the json file
with open(filename, mode = 'w') as fw:
json_string = "[\n\t{'boiler':"+str(boiler)+",'tower':"+str(tower)+"}\n]"
fw.write(json_string)
json_file_exists=1
else:
# append to the json file
char = ""
boiler = boiler + .01
tower = tower + .02
while(char<>"}"):
with open(filename, mode = 'rb+') as f:
f.seek(-1,2)
size=f.tell()
char = f.read()
if char == "}":
break
f.truncate(size-1)
with open(filename, mode = 'a') as fw:
json_string = "\n\t,{'boiler':"+str(boiler)+",'tower':"+str(tower)+"}\n]"
fw.seek(-1, os.SEEK_END)
fw.write(json_string)
count = count + 1

Categories

Resources