Python reading dictionary from file [duplicate] - python

This question already has answers here:
Reading JSON from a file [duplicate]
(7 answers)
Closed 1 year ago.
I am trying to read a dictionary from a JSON file which would look something like this.
{"#C": "C:\\Users\\user\\examplefolder}
I would like to load the dictionary from the file into filepath_dict. I am currently using this method to try this however, it refuses to load anything that is not a string.
import json
with open("filepaths.json", "r") as file:
file.write(json.loads(filepaths_dict))
How can I load the JSON dictionary into a python one?

Use json.load
with open("filepaths.json", "r") as f:
filepaths_dict = json.load(f)
json.loads: Will take a string
json.load: Will take a file
Also be careful about using the word "file" as a variable, you are overriding the built-in file function.

Related

How would I add a key/value pair to every single JSON file in a folder in python? [duplicate]

This question already has answers here:
How to add a key-value to JSON data retrieved from a file?
(3 answers)
Closed 6 months ago.
I have a folder containing ~10000 JSON files, and I'm looking to add a new identical key/value pair ("Symbol": "PPF") to each one.
Each JSON file is named using an increasing number: 0.json, 1.json, 2.json, ... 9999.json, 10000.json
My current best attempt was trying to remove the last line of every file (the final }), then append ,"Symbol": "PPF".
What would be the fastest way of adding that key/value pair to all JSON files?
Try the following looping over the files:
# Read a json file temp.json and convert to Python dict
import json
with open('temp.json') as f:
data = json.load(f)
data["key"] = "value"
# Write back to file
with open('temp.json', 'w') as f:
json.dump(data, f)

Python: create a file object from a string [duplicate]

This question already has answers here:
How do I wrap a string in a file in Python?
(4 answers)
Closed 9 months ago.
TLDR: How to create in Python a file object (preferably a io.TextIOWrapper, but anything with a readline() and a close() method would probably do) from a string ? I would like something like
f = textiowrapper_from_string("Hello\n")
s = f.readline()
f.close()
print(s)
to return "Hello".
Motivation: I have to modify an existing Python program as follows: the program stores a list (used as a stack) of file objects (more precisely, io.TextIOWrapper's) that it can "pop" from and then read line-by-line:
f = files[-1]
line = f.readline()
...
files.pop().close()
The change I need to do is that sometimes, I need to push into the stack a string, and I want to be able to keep the other parts of the program unchanged, that is, I would like to add a line like:
files.append(textiowrapper_from_string("Hello\n"))
Or maybe there is another method, allowing minimal changes on the existing program ?
There's io.StringIO:
from io import StringIO
files.append(StringIO("Hello\n"))

function to read json data from file and convert t into a list [duplicate]

This question already has answers here:
Reading JSON from a file [duplicate]
(7 answers)
Closed 1 year ago.
What code can I write to read python data from a json file I save and then convert it into a list?
Here is some sample code:
def read_json_file(filename):
"""
reads from a json file and saves the result in a list named data
"""
with open(filename, 'r') as fp:
# INSERT THE MISSING PIECE OF CODE HERE
data = json.loads(content)
return data
To import a json file, I recommend using the json libary.
In your example, you would first need to import it.
import json
Then you can use
with open('filename.json', 'r') as fp:
data = json.load(fp)
to get the data. Note that load is different from 'loads' (https://docs.python.org/2/library/json.html). You just need to change 'content' to 'fp' since that is how you referred to your file.
Note that this code stores returns the json as a dict, not as a list, which is different than what you are asking about, but probably what you want to use not knowing more about what you are trying to do.
You can basically use the builtin json module. Full documentation here : https://docs.python.org/3/library/json.html
To get a json string from object (any data like list, dict, etc...), use :
import json
json_str = json.dumps(my_data) # Get json string representation of my_data
fp.write(json_str) # Write json_str string to file fp
Once you wrote your file you can read the json string from file with :
json_str = fp.read()
And finally turn to a python object :
import json
my_data = json.loads(json_str)

How to write JSON to a file with a generic name? [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Which is the preferred way to concatenate a string in Python? [duplicate]
(12 answers)
Closed 3 years ago.
I'm writing a script that works with certain vocabulary. As a part of it, I want to store the incoming json data of a word in a file. The following code works only for one word at a time. But it will replace the data.json file every time with the json information of the new word.
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
What I'm trying to achieve is: I would like to store the json of each file separately.
For eg: if the word is "internet", then I want the file to export internet.json and if the word is "persistence," then i want the json to store persistence.json
I tried the below, but it throws a syntax error:.
with open(word||'.json', 'w') as outfile:
json.dump(data, outfile)
I'm new to Python (using Python3) and I'm working on a pet-project. So, it would be a great support if you can help me in achieving this. Thanks in advance.

Python Read File Content [duplicate]

This question already has answers here:
Easiest way to read/write a file's content in Python
(7 answers)
Closed 6 years ago.
In Python, how to read a file content only (not including attribute and filename), like using InputStream in Java?
I need a method that works for various file formats
I've tried this
with open(filePath, "rb") as imageFile:
str = base64.b64encode(imageFile.read())
M=str.decode()
print(M)
The problem is, I will get error for any object after that block
The most basic way is like so:
with open("filename.txt") as f:
contents = f.read()
The variable contents will now contain a string of everything in the file. More information is in the Python Documentation (https://docs.python.org/3/tutorial/inputoutput.html).

Categories