I was try to dump and load dictionary to json file using Python. I can dump file without a problem. However, when i try to load file into temp dictionary, error occur. I can not figure out the issue, Can anyone can help me on this ?Thanks
import os
import json
def get_stored_birth():
filename ='C:/Users/Sam/name.json'
temp = {}
with open(filename,'r+') as f_obj1:
temp =json.load(f_obj1)
print(temp.get(name),"is the birthday of",name)
def get_new_birth():
birth=str(input())
my_dict[name]=birth
print("Birthday database updated")
filename ='C:/Users/Sam/name.json'
with open(filename,'a') as f_obj:
f_obj.write('\n')
json.dump(my_dict,f_obj)
return name
my_dict={}
def quit():
"""This function quit program"""
return quit
while True:
filename ='C:/Users/Sam/name.json'
print("Enter a name:(blank to quit)")
name= str(input())
if name=="":
exit()
if name in my_dict:
name= get_stored_birth()
else:
print("I dont have info for",name)
print("What is their birthday")
name= get_new_birth()
The traceback as follow:
Traceback (most recent call last):
File "C:\Users\Sam\Desktop\Tianxu_Assignment2\Assignment 2.py", line 45, in <module>
name= get_stored_birth()
File "C:\Users\Sam\Desktop\Tianxu_Assignment2\Assignment 2.py", line 10, in get_stored_birth
temp =json.load(f_obj1)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 3 column 1 (char 12)
Problem solved !!!
1. replace with open(filename, 'a') as f_obj with replace with open(filename, 'w')
2.
if name in my_dict:
should not check my_dict !!! every time start a program will use new "dictionary". I move
filename ='C:/Users/Sam/name.json'
temp = {}
with open(filename,'r+') as f_obj1:
temp =json.load(f_obj1)
to main loop and check if name in temp:
Thanks guys!!!
You are appending new json to previous jsons you have created. Just substitute this line:
with open(filename,'a') as f_obj:
with this one:
with open(filename,'w') as f_obj:
Related
So I was making a poll/voting system for fun using JSON, and I encountered this error when I was coding it:
Traceback (most recent call last):
File "C:\Users\ooich\PycharmProjects\16dec2022\main.py", line 48, in <module>
poll()
File "C:\Users\ooich\PycharmProjects\16dec2022\main.py", line 32, in poll
fp = json.load(f)
File "C:\Python310\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python310\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I don't really understand 100% of what it means, given I have not touched code for over ~6 months.
Here's my code:
import json
def poll():
with open("poll.json", "r") as f:
fp = json.load(f)
le = fp.keys()
print(f"What would you like to vote?\n {le}")
i = input("Please write: ")
if fp.get(i) is None:
print("Key not found.")
return False
with open("poll.json", "w") as fe:
fep = json.load(fe)
fep[i] += 1
json.dump(fep, fe)
print("Voted!")
return True
poll()
Please do let me know if I missed something or you know how to solve it. Thanks.
I am guessing your json file is empty the same error as you when my json fill "poll.json" is empty.
with this json
poll.json
{"plop": 0}
and this python
import json
def poll():
with open("poll.json", "r") as f:
fp = json.load(f)
le = fp.keys()
print(f"What would you like to vote?\n {le}")
i = input("Please write: ")
if fp.get(i) is None:
print("Key not found.")
return False
with open("poll.json", "w") as f:
fp[i] += 1
json.dump(fp, f)
print("Voted!")
return True
poll()
result for ok
What would you like to vote?
dict_keys(['plop'])
Please write: plop
Voted!
result if no key present in json
What would you like to vote?
dict_keys(['plop'])
Please write: not
Key not found.
I've written a tkinter app in Python 3.7, which extracts from main CSV, pre-filtered by user, information into smaller reports. My issue is that while writing filtered data from main CSV into report I occasionally get a PermissionError:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\mdiakuly\AppData\Roaming\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "D:/PycharmProjects/report_extractor_hil_sil/report_extractor.py", line 286, in report_generation_prep
self.report_generation(names_list, relevant_params, specific_value, extracted_file)
File "D:/PycharmProjects/report_extractor_hil_sil/report_extractor.py", line 344, in report_generation
processing_data(rd,column)
File "D:/PycharmProjects/report_extractor_hil_sil/report_extractor.py", line 336, in processing_data
writing_new_report(gathering_row)
File "D:/PycharmProjects/report_extractor_hil_sil/report_extractor.py", line 299, in writing_new_report
with open(extracted_file, 'a+', newline='') as write_in:
PermissionError: [Errno 13] Permission denied: 'C:/Users/myusername/Desktop/reporter/Partial_report_14_10_2021T15-13-12.csv'
Once it has extracted only one row and through an error, another time it did whole extraction with no error, and few other times it extracted thousands of rows and through an error.
CSV file which is being written into was never opened during info extraction.
Has anyone faced the same issue or maybe has an idea how to fix it?
def writing_new_report(complete_row):
with open(extracted_file, 'a+', newline='') as write_in:
wt = csv.DictWriter(write_in, delimiter=';', fieldnames=relevant_params)
if self.debug:
print(complete_row)
wt.writerow(complete_row)
def processing_data(r_d,column='def'):
for idx, row in enumerate(r_d): #looping through major csv
self.progress.update()
if self.debug:
print(f'{idx:}',end=' / ')
gathering_row = {}
if column != 'def':
if row[column] not in names_list:
continue
else:
names_list.remove(row[column])
pass
else:
pass
for param, value in zip(relevant_params,specific_value):
self.progress.update()
if self.debug:
print(f'{row[param]:}',end=' / ')
gathering_row[param] = row[param]
if value == '---- All ----':
pass
elif value != row[param]:
if self.debug:
print(f'{row[param]:} - Skipped')
break
if param == relevant_params[len(relevant_params)-1]:
if self.debug:
print(f'{row[param]:} - Written')
writing_new_report(gathering_row)
New to coding and running through the exercises in Python Crash Course version 2. One of the exercises involves creating a file called "remember_me.py" and as far as I can tell, I'm entering the code as it exists in the book almost verbatim, but getting an error:
"""Exercise for Python Crash Course."""
import json
#Load the username, if it has been stored previously.
#Otherwise, prompt for the username and store it.
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input("What is your name?\n")
with open(filename, 'w') as f:
json.dump(username, f)
print(f"We'll remember you when you come back, {username}!")
else:
print(f"Welcome back, {username}!")
Whenever I try to run it, I get the following traceback (I replaced the username with "me" here):
Traceback (most recent call last):
File "C:\Users\me\Desktop\python_work\remember_me.py", line 9, in <module>
username = json.load(f)
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Any ideas what I'm doing wrong? I've tried just starting from scratch and re-typing, but apparently I'm making the same error!
import json
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input("What is your name? ")
with open(filename, 'w') as f:
json.dump(username, f)
print(f"We'll remember you when you come back, {username}!")
except json.decoder.JSONDecodeError: # This error is for when the json file is EMPTY.
username = input("What is your name? ")
with open(filename, 'w') as f:
json.dump(username, f)
print(f"We'll remember you when you come back, {username}!")
else:
print(f"Welcome back, {username}!")
def get_stored_number():
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
return None
**except json.decoder.JSONDecodeError:
return None**
else:
return username
number()
Solve this problem adding except for blank file username.json
i want replace unicode character to a file with python
this is my code :
with codecs.open('/etc/bluetooth/main.conf', "r", "utf8") as fi:
mainconf=fi.read()
forrep = ''.decode('utf8')
for line in mainconf.splitlines():
if('Name = ' in line):
forrep = line.split('=')[1]
print 'name',type(name)
print 'mainconf',type(mainconf)
print 'forrep',type(forrep)
mainconf = mainconf.replace(forrep, name)
#mainconf = mainconf.replace(forrep.decode('utf8'),' '+name)
with codecs.open('/etc/bluetooth/main.conf','w',"utf8") as fi:
fi.write(mainconf)
but python always get me error MemoryError...
this out :
name <type 'unicode'>
mainconf <type 'unicode'>
forrep <type 'unicode'>
Traceback (most recent call last):
File "WORK/Bluetooth/Bluetooth.py", line 359, in <module>
if __name__ == '__main__':main()
File "WORK/Bluetooth/Bluetooth.py", line 336, in main
BLMan.SetAllHCIName(common.cfg.get('BLUETOOTH', 'HCI_DEVICE_NAME'))
File "WORK/Bluetooth/Bluetooth.py", line 194, in SetAllHCIName
mainconf = mainconf.replace(forrep, name)
MemoryError
Iterate over the file object, you are storing the whole file content in memory using mainconf=fi.read() :
with codecs.open('/etc/bluetooth/main.conf', "r", "utf8") as fi:
for line in fi:
You store all the lines with read then you store a list of all the lines using splitlines so you are storing all the file content twice and as #abarnet pointed out in a comment you then try to store a third copy with
mainconf = mainconf.replace(forrep, name).
Iterating over the file object will give you a line at a time, if you need to store the lines after replacing do so each time through the loop so at most you will only have one copy of the file content in memory.
I have no idea what name is but writing to a tempfile will be the most efficient way to do what you want:
from tempfile import NamedTemporaryFile
with open('/etc/bluetooth/main.conf') as fi, NamedTemporaryFile(dir=".", delete=False) as out:
for line in fi:
if line.startswith("Name ="):
a, b = line.split("=",1)
out.write("{} = {}".format(a, name.encode("utf-8")))
else:
out.write(line)
move(out.name, '/etc/bluetooth/main.conf')
I'm trying to have the use enter an input for a file name, what I would like to do is just have the user type in the name of the file without the extension. Since the only applicable file will be a .txt file it seems redundant to have the user type the extension, so I would like to add the file extension with the code this is what I have so far:
def create_bills(filename, capacity):
f = open(filename)
mytable = mkHashTable(capacity)
for line in f:
txt = line.strip().split(' $')
person = Person(txt[0], txt[1])
if not person.name in keys(mytable):
mytable = put(mytable, person.name, person.bill)
elif person.name in keys(mytable):
index = indexOf(mytable, person.name)
else:
pass
def main():
capacity = int(input("Size of Hashtable: "))
file = input("Enter file to be read: ")
filename = (file +'.txt')
create_bills(filename, capacity)
I am unsure of how to actually approach this problem and add the .txt to the user input.
Example:
Please enter a file name:
help
.... help.txt
error:
Traceback (most recent call last):
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 30, in <module>
main()
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 28, in main
create_bills(filename, capacity)
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 12, in create_bills
f = open(filename, '.txt')
ValueError: invalid mode: '.txt'
In main you are already adding .txt to the file name entered by the user. You do not need to add it again in the open call in create_bills().