def prepend(line, path):
"""
Appends *line* to the _beginning_ of the file at the given *path*.
If *line* doesn't end in a newline one will be appended to the end of it.
"""
if isinstance(line, str):
line = line.encode('utf-8')
if not line.endswith(b'\n'):
line += b'\n'
temp = tempfile.NamedTemporaryFile('wb')
temp_name = temp.name # We really only need a random path-safe name
temp.close()
with open(temp_name, 'wb') as temp:
temp.write(line)
with open(path, 'rb') as r:
temp.write(r.read())
# Now replace the original with the modified version
shutil.move(temp_name, path)
评论列表
文章目录