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

前端 未结 4 1417
孤街浪徒
孤街浪徒 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条回答
  •  天命终不由人
    2021-01-01 20:36

    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.)

提交回复
热议问题