Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Pythonic way to store a data block in a Python script?

Perl allows me to use the __DATA__ token in a script to mark the start of a data block. I can read the data using the DATA filehandle. What's the Pythonic way to store a data block in a script?

like image 738
Charlie Guo Avatar asked Aug 04 '11 14:08

Charlie Guo


People also ask

What is Pythonic code?

What does Pythonic mean? When people talk about pythonic code, they mean that the code uses Python idioms well, that it's natural or displays fluency in the language. In other words, it means the most widely adopted idioms that are adopted by the Python community.


2 Answers

It depends on your data, but dict literals and multi-line strings are both really good ways.

state_abbr = {
    'MA': 'Massachusetts',
    'MI': 'Michigan',
    'MS': 'Mississippi',
    'MN': 'Minnesota',
    'MO': 'Missouri',
    }

gettysburg = """
Four score and seven years ago,
our fathers brought forth on this continent
a new nation, 
conceived in liberty
and dedicated to the proposition
that all men are created equal.
"""
like image 132
Ned Batchelder Avatar answered Sep 21 '22 06:09

Ned Batchelder


Use the StringIO module to create an in-source file-like object:

from StringIO import StringIO

textdata = """\
Now is the winter of our discontent,
Made glorious summer by this sun of York.
"""

# in place of __DATA__ = open('richard3.txt')
__DATA__ = StringIO(textdata)
for d in __DATA__:
    print d

__DATA__.seek(0)
print __DATA__.readline()

Prints:

Now is the winter of our discontent,

Made glorious summer by this sun of York.

Now is the winter of our discontent,

(I just called this __DATA__ to align with your original question. In practice, this would not be good Python naming style - something like datafile would be more appropriate.)

like image 40
PaulMcG Avatar answered Sep 18 '22 06:09

PaulMcG