0
contacts = {}
#trying to insert read code here to read from text file to a dictionary   



with open('Contacts.txt', 'a+') as contacts_file:
    contacts_file.write(str(str(contacts)))




contacts_file.close()

Disclaimer: Noob at python I am trying to create an address book/contact book. Yes, I know this could be done easier with classes and whatnot, but I have not learned them yet, and have gotten too far to rewrite the whole thing for my taste.

What the problem is for me, is that the output at the end of the code works fine and shows up good in the txt file, however I want to read that output back into a dictionary in python whenever the python file is started so I can modify/delete/search rather then just adding.

thesturggler
  • 62
  • 1
  • 6
  • 2
    you want to look at using [json files](https://docs.python.org/3/library/json.html) with `contacts_dict = json.load(contacts_file)` and `json.dump(contacts_dict)` – JL Peyret Mar 24 '20 at 20:05
  • make a much simpler dict and play with file I/O on it. if you have problems, you can ask here. but, right now, you have a bit too much code (that probably works) dealing with contact information, rather than what you are asking about, which is **only** files and Python dictionaries. welcome aboard. – JL Peyret Mar 24 '20 at 20:09
  • When done, the IDLE responds with ```json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```. Also, thanks for the welcome. Edit: Oh, is this because the files are not in the json format? – thesturggler Mar 24 '20 at 20:12
  • nah, write up some code and post it. I have no clue what you did, so I can't comment. json files have a special format, which you can test out at places like https://jsonlint.com/ Keep in mind 1 thing though: json only handles primitives like lists, dictionaries, numbers, strings and booleans. don't try to put classes into directly, though there are ways to work around. You can also try yaml which does the same things as json, but has a nicer(?) file format. https://pypi.org/project/PyYAML/ – JL Peyret Mar 24 '20 at 20:16
  • last, you may want to consider a real editor. VS code is a freebie for example. – JL Peyret Mar 24 '20 at 20:19
  • oh, I meant paste your **simplified** code here. I use NoScript, so no dice on external pasters. Plus, people will typically not look at external code before deciding to help/not help on your question. I mean, they are worthwhile for things like HTML+JS+CSS, but Python code mostly can be posted here. Generally try to make your posted code as simple as possible, trim out all the stuff that doesn't relate to your immediate question and post the output/error code, along with your expectations of what you wanted. There's a how to write good questions guide here too, but that's the gist. – JL Peyret Mar 24 '20 at 20:21
  • and, yes, existing question. I should have checked that. but hopefully you get the idea wrt Stackoverflow question format – JL Peyret Mar 24 '20 at 20:33

1 Answers1

1

I would not expect json to work in mode=a appends. If you play with it online you'll see why: adding a line at the end nukes the format.

So here's some code that tries reading it, adds a new contact, and saves it. You'll pretty much have to load the whole thing, modify it, then save it again.

import json

fnp = "contacts.json"
try:
    with open(fnp, "r") as fi:
        my_contacts = json.load(fi)
except (IOError,) as e: 
    my_contacts = {}

my_contacts["Phil"] = dict(email="phil@example.com")


with open(fnp, "w") as fo:
    json.dump(my_contacts, fo)


with open(fnp, "r") as fi:
    my_contacts2 = json.load(fi)

print(my_contacts2)

output:

not json format, as that wants ", not '.

{'Phil': {'email': 'phil@example.com'}}
JL Peyret
  • 10,917
  • 2
  • 54
  • 73
  • Oh, and pickle, as in some of the suggestions on duplicate question? security risk, unless you trust the data explicitly, meaning that no user is entering it - pickle basically runs python code as instructed in the file. yaml has that too, to a much lesser extent. json is least likely to have security problems. – JL Peyret Mar 24 '20 at 21:09
  • no worries. here's the security aspect for pickle. https://security.stackexchange.com/questions/183966/safely-load-a-pickle-file pickle's fast, and it avoids the need to only deal with primitives - json & python are really annoying with that - even a datetime will annoy you. but it's just a massive security risk so dont use it unless you a) are sure it's safe and b) you have really good reason. if you have python json serialization dump errors, **do** check carefully what's on SO - there's a ton of question/answers. – JL Peyret Mar 24 '20 at 21:24
  • one last thing: as you type in your question, look to the right of the screen. often, the SO system will pick up similar questions from what you are writing up and it often does it better than from the search bar. that often avoids duplicates. – JL Peyret Mar 24 '20 at 21:26