Tried a program -if json file already exists do nothing and if it does not exist then ask for input and write that input to file.Error is coming when I give input
import json
name="first.json"
try:
r=open(name)
except FileNotFoundError:
e=open(name,"w")
a=input("Enter Name: ")
json.dump(e,a)
ForceBru
45.1k10 gold badges72 silver badges104 bronze badges
-
2"Error is coming" - what's the error?ForceBru– ForceBru2021年03月12日 10:28:08 +00:00Commented Mar 12, 2021 at 10:28
-
Enter Name: a r=open(name) FileNotFoundError: [Errno 2] No such file or directory: 'first.json'mudit jain– mudit jain2021年03月12日 10:32:01 +00:00Commented Mar 12, 2021 at 10:32
-
in function "json.dump(e,a)" first parameter is object to dump and second one is file objectuser3431635– user34316352021年03月12日 10:32:24 +00:00Commented Mar 12, 2021 at 10:32
-
Also,During handling of the above exception, another exception occurred: Traceback line 10, in <module> json.dump(e,a) File "C:.....\Python\Python39\lib\json_init_.py", line 179, in dump for chunk in iterable: File "C:......\Python\Python39\lib\json\encoder.py", line 438, in iterencode o = _default(o) File "C:\....Python39\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class_.__name__} ' TypeError: Object of type TextIOWrapper is not JSON serializablemudit jain– mudit jain2021年03月12日 10:34:16 +00:00Commented Mar 12, 2021 at 10:34
-
@user3431635 That was a very silly mistake of mine.Thanks.mudit jain– mudit jain2021年03月12日 10:37:42 +00:00Commented Mar 12, 2021 at 10:37
3 Answers 3
import json
name="test.json"
try:
r=open(name)
except FileNotFoundError:
with open(name,"w") as e:
a=input("Enter Name: ")
json.dump(a,e)
answered Mar 12, 2021 at 10:34
RJ Adriaansen
9,7192 gold badges16 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
json.dump takes data to be written into a file first and the file second.
So the code should be:
# json.dump(data, file)
json.dump(a,e)
Comments
Probably your problem is wrong input data. Script has not any error.
input {"1": 1} is worked
Comments
lang-py