Home > database >  How to use template when creating new python file on VScode?
How to use template when creating new python file on VScode?

Time:11-29

In my python file I always start with the following lines

import sys
import matplotlib as mpl
sys.append('C:\\MyPackages')

rc_fonts = {
    "text.usetex": True,
    'font.size': 20,
    'text.latex.preamble': r"\usepackage{bm}",
}
mpl.rcParams.update(rc_fonts)

Is there a way to indicate to VScode that each time I create a new file.py, it will start with the previous lines ?

For now, I copy/paste a 'template.py' but this is not really convenient.

And because I work with Windows, I also tried to add 'C:\MyPackages' to the user variables Path but it didn't work.

CodePudding user response:

For Doing this kind of repetitive task we can use snippets in VSCode.

Step 1 : Hit > shift ctrl p open command palette.

Step 2 : Select Snippets: Configure User Snippets

Step 3 : Select Python

Step 4 : paste below code in python.json file. change prefix value. like "prefix": "hedwin" so now when you type hedwin vscode will paste our code snippet

"": {
  "prefix": "",
  "body": [
    "import sys",
    "import matplotlib as mpl",
    "sys.append('C:\\\\MyPackages')",
    "",
    "rc_fonts = {",
    "    \"text.usetex\": True,",
    "    'font.size': 20,",
    "    'text.latex.preamble': r\"\\usepackage{bm}\",",
    "}",
    "mpl.rcParams.update(rc_fonts)"
  ],
  "description": ""
}

For making snippet : snippet generator

CodePudding user response:

You can use the extension File Templates.

Save a file python.py with your start content in the default template location. (see extension page, you have to set it in the settings)

Then use Ctrl N and select Python, give it a name and the file is created.

You can add variables and snippets to customize the instantiation.

  • Related