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.

Answer from asikorski on Stack Overflow
🌐
Opensource.com
opensource.com › article › 19 › 7 › save-and-load-data-python-json
Save and load Python data with JSON | Opensource.com
This is where the JSON Python module comes in: with open('mydata.json', 'w') as f: json.dump(team, f) This code block creates a file called mydata.json and opens it in write mode. The file is represented with the variable f (a completely arbitrary designation; you can use whatever variable name you like, such as file, FILE, output, or practically anything).
🌐
Reddit
reddit.com › r/learnpython › write json file to variable in python
r/learnpython on Reddit: write json file to variable in python
August 24, 2023 -

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?

Using Python to Parse a JSON Object Mar 6, 2026
r/PythonLearning
6mo ago
Handling JSON files with ease in Python May 29, 2022
r/Python
4y ago
Embed variables in JSON file Feb 21, 2022
r/learnprogramming
4y ago
More results from reddit.com
🌐
Vertabelo Academy
academy.vertabelo.com › course › python-json › writing-json-files › writing-to-json-file › convert-a-string-into-a-json-file
How to Read and Write JSON Files in Python | Learn Python | Vertabelo Academy
with open('data.json', 'w') as outfile: json.dump(data, outfile) Remember, json.dumps() converts the given data to a string. The json.dump() function writes that data to a specified file.
🌐
Quora
quora.com › How-do-I-save-JSON-data-as-variables-in-Python
How to save JSON data as variables in Python - Quora
Answer (1 of 2): Use the json library [1] - specifically the Json.load if the json data is in a file, or json.loads if the json data is already in a string format. the json.load (or json.loads) return a Python object which is the Python equivalent of the json data. So if for example the top le...
🌐
Python.org
discuss.python.org › python help
How do i save what i write in here to a json file? - Python Help - Discussions on Python.org
February 6, 2025 - How do i save what i write in here to a json file · If you want all of the text, give the start index as '1.0' (line 1, column 0) and the end index as 'end' · Note that after root.mainloop() returns, the widget won’t exist any longer, so here I’m getting it when the window closes:
Find elsewhere
🌐
Javatpoint
javatpoint.com › save-json-file-in-python
Save JSON File in Python - Javatpoint
Save json File in Python with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
🌐
Quora
quora.com › How-do-you-save-data-to-a-JSON-file-using-Python
How to save data to a JSON file using Python - Quora
Answer: Any dictionary can be written to an opened file directly using the json.dump() function (don’t forget to import json beforehand), passing the dictionary as first argument and the opened file handle as second argument. There are some optional arguments as well for customization.
🌐
GeeksforGeeks
geeksforgeeks.org › saving-text-json-and-csv-to-a-file-in-python
Saving Text, JSON, and CSV to a File in Python - GeeksforGeeks
December 29, 2020 - Unlike other programming languages such as Java and C++, Python is a strongly, dynamically-typed language. This means that we do not have to explicitly specify the data type of function arguments or return values. Python associates types with values rather than variable names.
🌐
Python Pool
pythonpool.com › home › how to › save python variables to a file: json, pickle, and text
Save Python Variables to a File: JSON, Pickle, and Text
July 13, 2026 - Use json.dump for JSON-compatible values and open the file with an explicit encoding. Use pickle only for trusted Python-specific data because loading an untrusted pickle can execute code. Use NumPy’s native save formats when preserving array dtype and shape is important. Read it with the matching format and version policy, then validate the structure before using it. ... Please don't do that, even as an example.
🌐
Medium
medium.com › @ryan_forrester_ › save-and-load-json-files-in-python-a-complete-guide-49a5760b8b49
Save and Load JSON Files in Python: A Complete Guide | by ryan | Medium
October 28, 2024 - Let’s explore how to work with them in Python, with clear examples you can use right away. Let’s start with the basics — saving a simple dictionary to a JSON file: import json # Your data user_data = { "name": "Alice Smith", "age": 28, "email": "alice@example.com", "interests": ["coding", "hiking", "photography"] } # Save to file with open("user_data.json", "w") as file: json.dump(user_data, file) What’s happening here?
🌐
JMP User Community
community.jmp.com › t5 › Discussions › How-to-set-variables-from-imported-json-file-jmp-Associative › td-p › 508084
Solved: How to set variables from imported json file / jmp Associative Array? - JMP User Community
June 9, 2023 - I am using Application Builder to develop a tool for data analytics with Python integration. I have created a button to export a user's parameter selections in case they want to re-upload those at a later time and perform the same data preprocessing. Currently, the way I export the parameters is I first script them to a csv (using Save Text File(...) ), then it can be opened as a jmp table and from there, the two columns (Variables and Values) can be set to an Associative Array and I also save that as a JSON file for use in a backend application.
🌐
Stack Overflow
stackoverflow.com › questions › 47370475 › parse-json-file-using-python-and-save-the-values-into-variables-and-arrays
Parse JSON file using Python and save the values into variables and arrays - Stack Overflow
November 19, 2017 - I want to parse the above json file and fetch the Name, Place, Path and store them into variables and then fetch city, landmark and pin and store them into arrays. How can i do this in Python. I've tried searching but all I could find is just reading the json file but not parsing it this way. ... import glob, os, json from pprint import pprint jsonfile = "testing.json" with open('C:/Users/dev/Desktop/JSONSTest/'+jsonfile) as data_file: data = json.load(data_file) pprint(data)
Top answer
1 of 16
3357

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.

2 of 16
347

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.