2

I have a shared folder that contains a text file that I want my program to reference as though it were a .py file. For example, my .txt file has a dictionary in it that I reference in my program. How do i import the dictionary from a text file? Do i read it in line by line? Or is there a way to trick python into thinking it is a .py file.

Here is a sample similar to my .txt file:

#There are some comments here and there

#lists of lists
equipment = [['equip1','hw','1122','3344'],['equip2','hp','1133','7777'],['equip3','ht','3333','2745']]

#dictionaries
carts = {'001':'Rev23', '002':'Rev11','003':'Rev7'}

#regular lists
stations = ("1", "2", "3", "4", "11", "Other") 
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Cole
  • 349
  • 5
  • 16
  • related: [Dynamically importing Python module](http://stackoverflow.com/q/3799545/4279) – jfs Mar 26 '14 at 20:35

2 Answers2

3

Looks like what you need is a JSON file.

Example: consider you have a source.txt with the following contents:

{"hello": "world"}

Then, in your python script, you can load the JSON data structure into the python dictionary by using json.load():

import json 

with open('source.txt', 'rb') as f:
    print json.load(f)

prints:

{u'hello': u'world'}

You can also use exec(), but I don't really recommend it. Here's an example just for educational purposes:

source.txt:

d = {"hello": "world"}

your script:

with open('test.txt', 'rb') as f:
    exec(f)
    print d

prints:

{'hello': 'world'}

Hope that helps.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Are .json files easy to edit? I want this file to be easily edited. – Cole Mar 26 '14 at 17:25
  • I have multiple dictionaries and lists in this reference file. Will they all be usable via this method? – Cole Mar 26 '14 at 17:31
  • @Cole is there a python code inside? could you show a sample contents? – alecxe Mar 26 '14 at 17:32
  • Sorry for not being clearer. I edited in an example. – Cole Mar 26 '14 at 17:39
  • @Cole well, the easiest option would be to convert the file to `.py` and import it. Also see http://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python. – alecxe Mar 26 '14 at 17:44
  • @Cole yeah, you should really trust the source if you'd go with this option. – alecxe Mar 26 '14 at 17:47
  • i tried that, but i can't figure out how to import the .py file from a shared network folder. Any ideas on how to do that? – Cole Mar 26 '14 at 17:48
  • @Cole there are options, check if any of the answers from http://stackoverflow.com/questions/4710588/importing-module-from-network help. – alecxe Mar 26 '14 at 17:52
3

If you completely trust the source .txt file, check out execfile.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237