Write Text And Populate a New File From Template with Python


The concern is documenting patterns for writing into a python file, in particular to:

  1. create an empty markdown file with the title from an input

1. open()

  • even though you don’t have to pass selector, it is recommended for the sake of readability

2. write()

  • the write() method writes a string to a stream
f = open('hello-world.txt', mode = 'wt', encoding = 'utf-8')
f.write('hello-world, again!)
  • which results in hello-world.txt with - even when done repeatedly (append would keep lines growing)
hello-world, again!

3. usecase: populate a new file with a template for documentation

  • The script creates a file with the title based on the user’s input
## Overview
The aim of this document is
### Use cases* common usage or referral tickets### Prerequisites* technical or knowledge
<!-- ... -->

3.1. test

  • I don’t know how to test for this side-effect, the fast/stupid way seems to be to check if the first line is identical to the one from the template (I guess you could count the number of lines or compare files, but this is just to learn new methods)
def test_template():
with open('./Demo/hello-world.md', mode='rt', encoding='utf-8') as template:
first_line = template.readline().strip()
assert first_line == "## Overview"

3.2. prod

  • not using the with-block
def _createFile(docPath):
newDoc = open(docPath, mode='wt', encoding='utf-8')
template = open('./zendesk/template.md', mode='rt', encoding='utf-8')

4. sources

Technical Support Engineer/Technical Writer (Snowplow Analytics). with a passion for Python / writing documentation. More about me: https://pavol.kutaj.com