How to save a changed item to an external file? (Python 3)
Question: I'm fairly new to python, but I'm making a script and I want one of the
functions to update a variable from another file. It works, but when I exit
the script and reload it, the changes aren't there anymore. For example (this
isn't my script):

    
    
    #File: changeFile.txt
    number = 0
    
    #File: changerFile.py
    def changeNumber():
        number += 1
    

If I retrieve _number_ during that session, it will return 1, but if I exit
out and go back in again and retrieve _number_ without calling changeNumber,
it returns 0.

How can I get the script to actually save the number edited in changeNumber to
changeFile.txt? As I said, I'm fairly new to python, but I've looked just
about everywhere on the Internet and couldn't really find an answer that
worked.

EDIT: Sorry, I forgot to include that in the actual script, there are other
values.

So I want to change number and have it save without deleting the other 10
values stored in that file.


Answer: Assuming, as you show, that `changeFile.txt` has no other content whatever,
then just change the function to:

    
    
    def changeNumber():
        global number  # will not possibly work w/o this, the way you posted!
        number += 1
        with open('changeFile.txt', 'w') as f:
            f.write('number = {}\n'.format(number))
    

ADDED: the OP edited the Q to mention (originally omitted!-) the crucial fact
that `changefile.txt` has other lines that need to be preserved as well as the
one that needs to be changed.

That, of course, changes everything -- but, Python can cope!-)

Just add `import fileinput` at the start of this module, and change the last
two lines of the above snippet (starting with `with`) to:

    
    
    for line in fileinput.input(['changefile.txt'], inplace=True):
        if line.startswith('number ');
            line = 'number = {}\n'.format(number)'
        print line,
    

This is the Python 2 solution (the OP didn't bother to tell us if using Py2 or
Py3, a crucial bit of info -- hey, who cares about making it **easy** rather
than **very hard** for willing volunteers to _help_ you, right?!-). If Python
3, change the last statement from `print line,` to

    
    
        print(line, end='')
    

to get exactly the same desired effect.

