How can I write my inventory program so that it reads and writes to a text file?
<p>Basically, I'm trying to write a fairly simple, user-friendly program for the repair shop I'm working at. We've been trying to figure out a good way to organize and track LCD usage, so I've been working on this thing as a possible option.</p>

<p>I need it to do a few other things, but my main concern right now is getting the dictionary to read from a text file, as well as write to it. For example, if someone updates the stock on an iPhone 4s, we should be able to close the program and have the new quantity show up in "check stock". As it stands now, as soon as you close the program, everything returns to default.</p>

<p>I've placed the code below in Gist - what can I do for this one? I'm still learning python and this is the first "real" thing I've really started working on, so there's still some concepts I'm having trouble with.</p>

<p><a href="https://gist.github.com/anonymous/8815a95b2431dbfcea41fdfa05381893" rel="nofollow">https://gist.github.com/anonymous/8815a95b2431dbfcea41fdfa05381893</a></p>

<p>To put you on the right track, here is a minimal example that reads a JSON text file in the same directory, modifies it, and then writes it back.</p>

<p>First, here is the JSON file:</p>

<p>data.txt</p>

<pre><code>{"milk": 5, "orange juice": 3, "cookies": 1}
</code></pre>

<p>Here is a program that reads this json file using the <a href="https://docs.python.org/2/library/json.html" rel="nofollow"><code>json</code></a> library to an <code>inventory</code> Python dictionary, increments "milk," and saves it back:</p>

<pre><code>import json

with open('data.txt', 'r') as f:
  inventory = json.loads(f.read())

inventory['milk'] += 1

with open('data.txt', 'w') as f:
  f.writelines(json.dumps(inventory))
</code></pre>

<p>You can add all the logic you want between the "reading" and "writing" step.</p>

python dictionary inventory