1

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)
5
  • 2
    "Error is coming" - what's the error? Commented Mar 12, 2021 at 10:28
  • Enter Name: a r=open(name) FileNotFoundError: [Errno 2] No such file or directory: 'first.json' Commented Mar 12, 2021 at 10:32
  • in function "json.dump(e,a)" first parameter is object to dump and second one is file object Commented 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 serializable Commented Mar 12, 2021 at 10:34
  • @user3431635 That was a very silly mistake of mine.Thanks. Commented Mar 12, 2021 at 10:37

3 Answers 3

2
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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

https://docs.python.org/3/library/json.html#json.dump

Comments

0

Probably your problem is wrong input data. Script has not any error. input {"1": 1} is worked

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.