How To Create A Python File In Ubuntu Terminal

This tutorial will guide you through creating a Python file in the terminal of your Ubuntu system. Creating a Python file and running it directly from the terminal might be useful in various situations, such as setting up automation scripts or testing smaller code snippets. Let’s dive into the step-by-step process to make your Python file and execute it using the terminal.

Step 1: Open Terminal

Press Ctrl + Alt + T on your keyboard to open the terminal, or you can search for the terminal in your system’s application menu and click on it to open it.

Step 2: Navigating to the desired directory

Execute the cd command to change the directory to the folder where you want to create the Python file. For instance:

This command will change the directory to the “python_projects” folder inside the “Documents/coding” directory.

If you are unsure about your current directory, use the pwd command to display the present working directory:

Step 3: Creating the Python file

To create a new Python file, use the touch command followed by the file name you’d like to use, with the “.py” extension at the end. For example:

This command creates a new Python file called “my_first_script.py” in the current directory.

Step 4: Editing the Python file

You can use the built-in Ubuntu text editor nano or any other text editor of your choice (like vim, emacs, etc.) to edit the Python file. To open the file in nano, type:

You will now see the text editor interface where you can enter and modify the contents of your Python file. For this example, let’s write a simple Python script to print “Hello, world!”:

After adding your desired Python code, press Ctrl + X then Y followed by Enter to save your changes and exit nano.

Step 5: Running the Python file

To execute the Python file, enter the following command in the terminal:

The output should display:

Hello, world!

Conclusion

Congratulations! You’ve now learned how to create a Python file in the terminal of your Ubuntu system, edit the file, and run it using the Python interpreter. This knowledge will enable you to quickly create and run Python scripts for various purposes, such as automating tasks, web scraping, or data processing.