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]

openGeditFromPythonInCommandPrompt

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!

Advertisement

2 thoughts on “Opening Files in a Text Editor from the CMD / Terminal (Using Python)

  1. You can also use os.startfile(_file) – this will open the file using the os’ defined application for the extension

    eg. if the extn is .text and you’ve associated .txt with sublime, it’ll open the file using sublime

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s