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

前端 未结 4 1414
孤街浪徒
孤街浪徒 2021-01-01 20:20

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 wa

4条回答
  •  萌比男神i
    2021-01-01 20:42

    IMO it highly depends on the type of data: if you have only text and can be sure that there is not ''' or """ which micht by any chance be inside, you can use this version of storing the text. But what to do if you want, for example, store some text where it is known that ''' or """ is there or might be there? Then it is adviseable to

    • either store the data coded in any way or
    • put it in a separate file

    Example: The text is

    There are many '''s and """s in Python libraries.

    In this case, it might be hard to do it via triple quote. So you can do

    __DATA__ = """There are many '''s and \"""s in Python libraries.""";
    print __DATA__
    

    But there you have to pay attention when editing or replacing the text. In this case, it might be more useful to do

    $ python -c 'import sys; print sys.stdin.read().encode("base64")'
    There are many '''s and """s in Python libraries.
    

    then you get

    VGhlcmUgYXJlIG1hbnkgJycncyBhbmQgIiIicyBpbiBQeXRob24gbGlicmFyaWVzLg==
    

    as output. Take this and put it into your script, such as in

    __DATA__ = 'VGhlcmUgYXJlIG1hbnkgJycncyBhbmQgIiIicyBpbiBQeXRob24gbGlicmFyaWVzLg=='.decode('base64')
    print __DATA__
    

    and see the result.

提交回复
热议问题