Python: Append Template String to New File
Shebang/Interpreter Directive
#!/usr/bin/env python3
Import os.system
from os import system
Path: Working Directory
PATH = '/home/foo/Documents/html/'
Input Filename
User prompted to enter name of file. .html
is automatically filled in. In this example, the text string foo
will be assigned to the fi
variable.
fi = input('Fill in the blank ________.html: ')
Template Text Stream
open()
function creates a file object for reading only, when the 'r'
parameter is passed to it. The template file path /home/foo/Documents/html/_template.html
is assigned to the name
parameter. read mode and UTF-8
encoding are defaults.
<_io.TextIOWrapper name='/home/foo/Documents/html/_template.html' mode='r' encoding='UTF-8'>
tr = open(PATH + '_template.html', 'r')
Template String
read()
method reads the file object assigned to tr
and returns a string.
ts = tr.read()
New File Text Stream
Passing the 'a'
parameter to the open()
function creates a file object for appending only. The new file’s path /home/foo/Documents/html/foo.html
is assigned to the name
parameter. UTF-8
encoding is a default. Since the template string from _template.html
will be appended to foo.html
using the write()
function.
<_io.TextIOWrapper name='/home/foo/Documents/html/foo.html' mode='a' encoding='UTF-8'>
The following try…finally block ensures file closure:
try:
nf = open(PATH + fi + '.html', 'a')
nf.write(ts)
finally:
nf.close()
System
os.system executes commands in the subshell:
chown 1000:1000 /home/foo/Documents/html/foo.html
chmod 755 /home/foo/Documents/html/foo.html
₁gedit /home/foo/Documents/html/foo.html
system('chown 1000:1000 ' + PATH + fi + '.html')
system('chmod 755 ' + PATH + fi + '.html')
system('gedit ' + PATH + fi + '.html')
₁. 644
and 755
are standard Unix permissions settings.