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?
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.
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.
"""
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With