title: Writing multiple variables to a file using a function
body: <p>I am writing a function that exports variables as a dictionary to an external file.
  The problem comes when calling that function from another script. I think it has something to do with the <code>globals()</code> parameter.</p>
  
  <pre><code>import sys
  import os
  
  mydict = {}  #'initialising" the an empty dictionary to be used locally in the function below
  
  def writeToValues(name):
      fileName = os.path.splitext(os.path.basename(sys.argv[0]))[0]
      valuePrint=open("values.py","a")
      def namestr(obj,namespace):
          return[name for name in namespace if namespace[name] is obj]
      b = namestr(name, globals())
      c = "".join(str(x) for x in b)
      mydict[(c)] = name
      valuePrint.write(fileName)
      valuePrint.write("=")
      valuePrint.write(str(mydict))
      valuePrint.write("\n")
      valuePrint.close()
      return mydict
  
  a = 2
  b = 3
  
  writeToValues(a)
  writeToValues(b)
  </code></pre>
  
  <p>I get the following result:</p>
  
  <pre class="lang-none prettyprint-override"><code>Main Junkfile={'a': 2, 'b': 3}
  </code></pre>
  
  <p>note the word <code>Main Junkfile</code> is the name of the script I ran as that is what the function first does, to get the name of the file and use that to name the dictionary.</p>
  
  <p>Now help me as I cannot generate the same if I import the function from another script.
  Another problem is that running the script twice generates the values in steps.</p>
  
  <pre class="lang-none prettyprint-override"><code>Main Junkfile={'a': 2}
  Main Junkfile={'b': 3, 'a': 2}
  </code></pre>
  
  <p>I cannot change the file open mode from append to write since I want to store values from other scripts, too.</p>