#๐Ÿ”’ main not running properly

37 messages ยท Page 1 of 1 (latest)

halcyon haven
#
import json

print("A to Add, R to Remove, S to Search")
with open("game_data.json") as f:
    data = json.load(f)

#Converting the list into an empty list.
data['People'] = []

def add_contacts(data):
    Name = input("Enter the name of the person you want to add: ")
    Phone = input("Enter the phone num of the person you want to add: ")
    EMail = input("Enter the email of the person you want to add: ")
    
    data['People'].append({
        "Name": Name,
        "Phone": Phone,
        "Email": EMail
    })
    print(f"{data['People'][Name]} has been added.")

def remove_contacts(data):
    Name = input("Enter the name of the person you want to delete: ")
    
    if data['People'][Name] in data['People']:
        del data['People'][Name]
    else:
        print("The name you entered is not in your contacts.")
    

    
def main():
    add_choice = input("Enter your action: ")
    if add_contacts == 'A':
        add_contacts(data)

    elif add_choice == 'R':
        remove_contacts(data)
    

main()
languid daggerBOT
#

@halcyon haven

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

halcyon haven
#
{
    "People": [
        {
            
        }
    ]
}
```json file
#

so what happens is

#

the main function runes

#

runs

#

but if i press A it just exits the program

wind current
#

@halcyon haven it looks like you never save the data back to the json file

halcyon haven
#

save?

wind current
#
with open("game_data.json") as f:
    data = json.load(f)

here, you are reading data from a file
if you want to change the file, you have to open it in write mode and write to the file

halcyon haven
#

oh

#

is that why it exits?

wind current
#

data represents the content of game_data.json at the time that you load it. it isn't "bound" to that json file--changes to data won't automatically change game_data.json

sinful wharf
#

add_contacts will never be A

halcyon haven
#

oh

#

i will write it

#

ok heres the thing

#
return loads(fp.read(),
                 ^^^^^^^^^
io.UnsupportedOperation: not readable
```This error and it prob occurs cause of this
```py
data['People'] = []
```right?
#

cuz like if its empty it cant read it?

wind current
halcyon haven
#
Traceback (most recent call last):
  File "e:\Python Work\ATM.py", line 5, in <module>
    data = json.load(f)
           ^^^^^^^^^^^^
  File "C:\Users\Hammad\AppData\Local\Programs\Python\Python312\Lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
                 ^^^^^^^^^
io.UnsupportedOperation: not readable
#

when i run this my json file becomes total blank

wind current
#
with open("game_data.json", 'w') as f:
    data = json.load(f)

did you add a w like this?

halcyon haven
#

yes

wind current
#

that means "write". you can't read a file if you opened it in write mode

halcyon haven
#

...

#

why is it reading it?

wind current
#

because you wrote json.load(f)

#

!docs json.dump

languid daggerBOT
#

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [Python-to-JSON conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).

Note

Unlike [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) and [`marshal`](https://docs.python.org/3/library/marshal.html#module-marshal), JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to [`dump()`](https://docs.python.org/3/library/json.html#json.dump) using the same *fp* will result in an invalid JSON file.
halcyon haven
#

!docs json.load

languid daggerBOT
#

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* to a Python object using the [JSON-to-Python conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).
wind current
#

load is for loading/reading and dump is for saving/writing

halcyon haven
#

ohhh i thought dump is only used when creating a new one

#

!close

languid daggerBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.