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") 
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Are .json files easy to edit? I want this file to be easily edited.
I have multiple dictionaries and lists in this reference file. Will they all be usable via this method?
@Cole is there a python code inside? could you show a sample contents?
Sorry for not being clearer. I edited in an example.
@Cole well, the easiest option would be to convert the file to .py and import it. Also see stackoverflow.com/questions/701802/….
|
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.