This content originally appeared on DEV Community and was authored by Hritik Pawar
If you are a Coder? We have to create a file with a basic syntax on regular basis.
In the last blog as I told you, I am learning some Competitive programming I have to create a new python file every time I learning and solving a new algorithm.
Also, each file has a main() function which I have to write every time, and also I have to update my readme.md file as I push it on GitHub and keep track of problems I solve.
So I created a simple template file using python which I can run from any directory. I just have to type "template" in cmd > enter new filename > enter the text I have to append to the readme.md file > and Enter.
It's that simple!
Code of my template.py file.
#imports
import os
from datetime import date, datetime
today = date.today()
now = datetime.now()
d1 = today.strftime("%B %d, %Y")
current_time = now.strftime("%H:%M:%S")
#file creation locations and file name input
Newfilename = input("Enter filename:")
readmefileinput = input("Enter readme input:")
Newfilelocation = Newfilename
ReadmeFileLocation = "readme.md"
#open file to read, write or append
f = open(Newfilelocation, "a")
g = open(ReadmeFileLocation, "a")
#Declaration of the lines to write
comments = "#Date: " + d1 + ' ' + "Time: " + current_time + "\n"
imports = "from sys import stdin, stdout\nimport collections\nimport time\n\n\n\n"
line1 = "def main():\n\n\n\n"
line2 = "if __name__ == '__main__:'\n "
line3 = " main()"
#Writelines in the file created
f.writelines ([comments, imports, line1, line2, line3])
g.write("\n" + readmefileinput)
f.close()
g.close()
To make Python scripts runnable from any location under Windows:
To call python script directly from the command prompt, e.g., to invoke the script “template.py” simply typing:
> template
instead of needing to type:
> python path\to\template.py
Steps to add template.py to Environment Variables:
Go to your python directory. E.g. Mine is "C:\Python39\Scripts"
Copy template.py file into this directory
It's more likely you already have a Python script folder in your Environment Variable but if not
Add the path to this script directory in Windows "PATH" system variable:
You should be able to run any of your python template files from any directory now.
This content originally appeared on DEV Community and was authored by Hritik Pawar

Hritik Pawar | Sciencx (2021-05-01T07:21:47+00:00) Python Automate the task of creating a file and run it from any directory.. Retrieved from https://www.scien.cx/2021/05/01/python-automate-the-task-of-creating-a-file-and-run-it-from-any-directory/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.