Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
877 views
in Technique[技术] by (71.8m points)

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

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 lists or dicts. It would be nice if I would be able to define template into separate file (like output.templ) instead of hardcoding it into source code.

As simple example what I want to achieve, we have variables title, subtitle and list

title = 'foo'
subtitle = 'bar'
list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

And running throught a template, output would look like this:

Foo
Bar

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

How to do this? Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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': '
'.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...