The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.
The easiest solution would be to close the file after you've read it in, then reopen it for writing.
with open("replayScript.json", "r") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
with open("replayScript.json", "w") as jsonFile:
json.dump(data, jsonFile)
Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.
with open("replayScript.json", "r+") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
jsonFile.seek(0) # rewind
json.dump(data, jsonFile)
jsonFile.truncate()
Answer from Shawn Chin on Stack OverflowThe issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.
The easiest solution would be to close the file after you've read it in, then reopen it for writing.
with open("replayScript.json", "r") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
with open("replayScript.json", "w") as jsonFile:
json.dump(data, jsonFile)
Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.
with open("replayScript.json", "r+") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
jsonFile.seek(0) # rewind
json.dump(data, jsonFile)
jsonFile.truncate()
def updateJsonFile():
jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
data = json.load(jsonFile) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file
## Working with buffered content
tmp = data["location"]
data["location"] = path
data["mode"] = "replay"
## Save our changes to JSON file
jsonFile = open("replayScript.json", "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()
My Code: Python, (Using discord rewrite if this matters)
user_id = str(ctx.message.author.id)
print(user_id)
# reads data
with open("test.json", "r") as f:
data = json.load(f)
print(data)
print(type(data))
# checks if user is in data
if user_id not in data['users'].__str__():
data.update({})
print(data)
# checks if data is type list
if type(data) is dict:
data = [data]
print(type(data))
# updates data with new user
data.append({"user_id": user_id})
print(data)
# writes new data to json file
with open("test.json", "w"):
json.dump(data, f)
Error Code: Command raised an exception: UnsupportedOperation: not writableYou would want to do something along the lines of:
def append_statistics(filepath, num_of_posts, followers, following):
with open(filepath, 'r') as fp:
information = json.load(fp)
information["statistics"].append({
"date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"num_of_posts": num_of_posts,
"followers": followers,
"following": following
})
with open(filepath, 'w') as fp:
json.dump(information, fp, indent=2)
You need to read the .json file and then append the new dataset and dump that data. See the code.
import json
appending_statistics_data = {}
appending_statistics_data["followers"] = 2346
appending_statistics_data["date"] = "2018-02-06 02:10:00"
appending_statistics_data["num_of_posts"] = 234
appending_statistics_data["following"] = 234
with open(file.json, 'r') as fp:
data = json.load(fp)
data['statistics'].append(appending_statistics_data)
#print(json.dumps(data,indent=4))
with open(file.json, 'w') as fp:
json.dump(data, fp, indent=2)
Hey all, I am learning about json in python and want to better understand how to edit json files, I understand how to add more data at the end of the file but i can't find anything online about how to edit the data in the file, what i want to do is change the values of things that are already put into the file. for example the file may have 'cat': 1.00 and i want to change the 1.00 to a user specified input can someone recommend some resources and videos that can help me with this as all i find is about adding data to the end. (P.s This is not a easily searchable question as ive looked on many sites like https://www.w3schools.com/python/python_json.asp and https://docs.python.org/3/library/json.html and https://realpython.com/python-json/ and there is nothing about overwriting data)
I'm trying to read through documentation, but I haven't found a direct way to do it. So Reddit we go.
I'm trying to replace a list of json data with a dictionary, because it makes it easier to do SimpleNamespace(**d) on everything. I have the dictionary, but how do I replace the data? I never really learned file IO, especially with json data.
I’m trying to write data to a txt file. The current script works but it overwrites the data within the txt file every time the script is run. Any help would be highly appreciated.
import json
data = {}
data['people'] = []
data['people'].append({
'name': 'Scott',
'website': 'stackabuse.com',
'from': 'Nebraska'
})
data['people'].append({
'name': 'Larry',
'website': 'google.com',
'from': 'Michigan'
})
data['people'].append({
'name': 'Tim',
'website': 'apple.com',
'from': 'Alabama'
})
with open('d.txt', 'w') as outfile:
json.dump(data, outfile)
with open('d.txt') as json_file:
data = json.load(json_file)
for p in data['people']:
print('Name: ' + p['name'])
print('Website: ' + p['website'])
print('From: ' + p['from'])
print('')How do you want it to work? You want to have it print the contents of the file? Then simply delete lines 3 - 24.
with open('d.txt', 'w') as outfile:
json.dump(data, outfile)
To append data, replace 'w' with 'a' or 'a+'. 'w' always writes up a new file, while 'a' loads the file, and appends the text at the bottom of the text file.
Look at the output file before and after running the code, and you should see what's going on.
Right before the json.dump, the file object points to the end of the file. You then dump data from this position.
If you try rewinding the file first, it should overwrite the data from the start:
fp.seek(0)
json.dump(temp, fp)
However, this could potentially leave dangling data beyond the first object, if it writes less data than is already in the file. I therefore suggest you restructure your code to read and write the file in two operations, wiping the file on the write. For example:
import json
filename = "foo"
print("Reading %s" % filename)
try:
with open(filename, "rt") as fp:
data = json.load(fp)
print("Data: %s" % data)
except IOError:
print("Could not read file, starting from scratch")
data = {}
# Add some data
data["key2"] = "value2"
print("Overwriting %s" % filename)
with open(filename, "wt") as fp:
json.dump(data, fp)
This depends on how you open the file. If you specify "w" by
with open(filename, "w") as f:
json.dump(data,f)
the previous data will be overwritten. But if you "a" or "a+"
with open(filename, "a") as f:
json.dump(data,f)
it would append the new data.
Ref: Python open()