Adding a template for new Python files in Emacs

I wanted my name and email address to appear in the top of the page every time I create a new python file in Emacs. So here’s what I did to achieve that.

First of all create a folder called templates in the .emacs.d directory (the .emacs.d directory is located in your home directory. If it does not exist, just create the directory ). Then create a file named template.py  in that directory. And add the text you want to be included when you create a new python file. An example can be shown as follows.

#Name: This Is My Name

#E-mail: someone@somewhere.lol

Then open the .emacs file in your home directory (if this doesn’t exist, simply create an empty file named .emacs). Then add the following content to the bottom of the .emcas.

;#############################################
;To load python templates

(add-hook 'find-file-hooks 'maybe-load-template)
(defun maybe-load-template ()
(interactive)
(when (and
(string-match "\\.py$" (buffer-file-name))
(eq 1 (point-max)))
(insert-file "~/.emacs.d/templates/template.py")))

That’s all…!. Now when ever you create a new python file using Emacs these header info will appear!.

More info:

As you might have observed this trick can be extended to other file types by changing the .py extension in the (insert-file “~/.emacs.d/templates/template.py”) line and creating a relevant template in the templates folder.

Also there are more advanced ways to achieve the same with more functionality in http://www.emacswiki.org/emacs/AutomaticFileHeaders

Share Button

One thought on “Adding a template for new Python files in Emacs

  1. The most common place to specify custom template tags and filters is inside a Django app. If they relate to an existing app, it makes sense to bundle them there; otherwise, they can be added to a new app. When a Django app is added to

Leave a Reply to neostamalur.science Cancel reply

Your email address will not be published. Required fields are marked *