Create a Python file in terminal

You can create a Python file directly from the terminal. Follow these steps to do it:

  1. Open Command Prompt (cmd).
  2. Open the Python interpreter by typing python inside the terminal.
  1. Open (or create if it doesn’t exist) a new file for writing inside an existing directory.
my_file = open("D:/temp/python_file.py", "w+")
  1. The file is created. Now, you can write to it. Create a loop:
for i in range(6):
  1. Add a text you want to repeat. Remember to add an indentation at the beginning.
my_file.write("This is line number %d\n." % (i+1))
  1. It’s a good practice to close the file after the process:
my_file.close()

The full code:

my_file = open("D:/temp/python_file.py", "w+")

for i in range(6):
    my_file.write("This is line number %d." % (i + 1))

my_file.close()