You should open the file specifying the open mode if it's different than read:
with open ("userNames.txt", "w") as f:
f.write(name)
open with no mode provided opens the file in read mode by default, no surprise it's not writable.
By the way, what's the point of opening the file twice? Lines
saveUserInp = open("userNames.txt", 'w')
...
saveUserInp.close()
might be removed since you open file with the with statement.
I have a file
state_info.txt
state1: New york size: 302.6 mi² state2: connecticut size2: 5,028 mi²
What im trying to do is take the content in this file and convert it to json and save it as
a python variable named JSON_DUMP so that I can use it for a request to post a message
READFILE = open('state_info.txt', "r")JSON_DUMP = print(READFILE.read())
print(f'Sending to geography channel')
SEND_MSG = requests.post(url=WEBHOOK, json=JSON_DUMP) print(SEND_MSG)
However, this gives me a 400 error and i'm not sure why.
If I use this variable below
JSON_STUFF = {"text": 'US States Information provided'}
SEND_MSG = requests.post(url=WEBHOOK, json=JSON_STUFF)print(SEND_MSG)
I get a 200 and the message gets sent so I know the WEBHOOK works properly and message will send but the state_info.txt file may change when more people add information to it.
Is there a way to take the contents of a file and save it as JSON "variable" for python to then use in a request response?
There seems to be ways to save data to a file, take variables and write them to files, but im trying to do the opposite? Anyone know if this could be done?
Let's say I want to write two lists and a dict to a JSON file. I can do so with the following code:
import json
x = [1, 2, 3]
y = [4, 5, 6]
z = {"1": 1, "2": 2}
with open("test.json", "a", encoding="utf-8") as f:
json.dump(x, f)
json.dump(y, f)
json.dump(z, f)But what if I want the variable names written to the file as well? My goal is to be able to read / write / append to the two lists and the dict at a later time. To do so, I would need to access them by variable name. How can I achieve this?
Create the data structure that you want (in your case, a list containing a dictionary), and call json.dump().
with open("file.json", "w") as f:
json.dump([{"f_name": f_name, "l_name": l_name}], f)
Don't use wb mode when creating a JSON file. JSON is text, not binary.
You can create the list of dictionaries, and then use https://docs.python.org/3/library/json.html#json.dump to write it into the file
import json
f_name= 'first name'
l_name= 'last name'
#Create the list of dictionary
result = [{'f_name': f_name, 'l_name': l_name}]
import json
with open("file.json", "w") as f:
#Write it to file
json.dump(result, f)
The content of the json file would look like
[{"f_name": "first name", "l_name": "last name"}]
Yes. You can use the json module. Specifically json.loads. However, if you also want a key value association between your data, you'll need to use a dictionary:
from json import loads
json_data = \
"""
[
[1, "Apple"],
[2, "Orange"],
[3, "Grapes"],
[4, "Banana"],
[5, "Mango"]
]
"""
data = dict(loads(json_data))
print(data)
# {1: u'Apple', 2: u'Orange', 3: u'Grapes', 4: u'Banana', 5: u'Mango'}
Unsurprisingly, you need the json module.
In [29]: import json
In [30]: data = '''[
...: [
...: 1,
...: "Apple"
...: ],
...: [
...: 2,
...: "Orange"
...: ],
...: [
...: 3,
...: "Grapes"
...: ],
...: [
...: 4,
...: "Banana"
...: ],
...: [
...: 5,
...: "Mango"
...: ]
...: ]'''
In [31]: json.loads(data)
Out[31]: [[1, 'Apple'], [2, 'Orange'], [3, 'Grapes'], [4, 'Banana'], [5, 'Mango']]
The module also contains functions to handle data in files.
To extract the fruit names by numerical key could be done in several ways, but they all involve transforming the data further. For example:
In [32]: fruits = []
In [33]: for key, name in json.loads(data):
...: fruits.append(name)
...:
In [34]: fruits[0]
Out[34]: 'Apple'
Here Python's zero-based indexing slightly defeats the value of this solution given that the keys start with 1. A dictionary gives you exactly what you need. If you call the dict constructor with a list of pairs it will treat them as key, value pairs.
In [35]: fruits = dict(json.loads(data))
In [36]: fruits[1]
Out[36]: 'Apple'
I've been working with Dictionaries for about 6 months and I'm about to redesign my program to use objects instead (which is what it should have used, but I didn't have the knowledge yet). I have been saving the dictionaries as JSON between web pages with json dump.
My question is, what is the best way to save an object to a JSON file? I'm looking for best practice at this point rather than my old method of 'quick and dirty'.
Thanks.
You don't need to store each value of JSON in a new variable, you can use a python dictionary.
See JSON and Python Dictionary
import json
#opening json file
with open("data.json") as f:
#converting json to python dict and stroing it in data variable
data = json.loads(f.read())
#iterating dict items and printing values
for items in data:
print(items['id'],items['name'],items['price'])
#you can also access dict values like this
#0 is the index number.
print(data[0]['id'])
print(data[0]['name'])
print(data[0]['price'])
#similarly
print(data[1]['id'])
print(data[2]['id'])
You can simply use json module with python dictionary as follow:
# Import the module
import json
# String with JSON format
data_JSON = """
[
{
"id": "p01",
"name": "Name 1",
"price": 1,
"quantity": 1
},
{
"id": "p02",
"name": "Name 2",
"price": 2,
"quantity": 2
},
{
"id": "p03",
"name": "Name 3",
"price": 3,
"quantity": 3
}
]
"""
# Convert JSON string to dictionary
data_dict = json.loads(data_JSON)
print(data_dict)
data is a Python dictionary. It needs to be encoded as JSON before writing.
Use this for maximum compatibility (Python 2 and 3):
import json
with open('data.json', 'w') as f:
json.dump(data, f)
On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
See json documentation.
To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:
import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False))
The code is simpler in Python 3:
import json
with open('data.txt', 'w') as f:
json.dump(data, f, ensure_ascii=False)
On Windows, the encoding='utf-8' argument to open is still necessary.
To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:
import json, codecs
with open('data.txt', 'wb') as f:
json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)
The codecs.getwriter call is redundant in Python 3 but required for Python 2
Readability and size:
The use of ensure_ascii=False gives better readability and smaller size:
>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'
>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17
Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.