Is there a native templating system for plain text files in Python?

后端 未结 4 609
盖世英雄少女心
盖世英雄少女心 2020-11-30 18:20

I am looking for either technique or templating system for Python for formatting output to simple text. What I require is that it will be able to iterate through multiple li

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 19:19

    You can use the standard library string an its Template class.

    Having a file foo.txt:

    $title
    $subtitle
    $list
    

    And the processing of the file (example.py):

    from string import Template
    
    d = {
        'title': 'This is the title',
        'subtitle': 'And this is the subtitle',
        'list': '\n'.join(['first', 'second', 'third'])
    }
    
    with open('foo.txt', 'r') as f:
        src = Template(f.read())
        result = src.substitute(d)
        print(result)
    

    Then run it:

    $ python example.py
    This is the title
    And this is the subtitle
    first
    second
    third
    

提交回复
热议问题