Opening Files in a Text Editor from the CMD / Terminal (Using Python)

Motivation for this blog post:

I recently had to edit the .bashrc file in Ubuntu and comment / delete a subset of its contents. The file .bashrc had to be located (home directory) and opened in a text editor. The file isn’t visible in the desktop environment, so it can’t be opened from there, so I had to use bash. I’m no command line expert, so I used Python to open and edit the file. I intended to open the file in gedit text editor, so I had to run Python from the directory containing .bashrc. [Click image below to enlarge]


Which opened up .bashrc

Screenshot from 2015-09-26 13:46:01

Put simply:

Opening a file in text editor is a matter of two simple lines of code. First, navigate to the directory containing the file you wish to open in a text editor (such as gedit) in bash or terminal or CMD. Then type the following:

$ python
>>> import sys, os
>>> os.system("<text editor> <file name with extension>")

That’s all there is to it!