5

How do I open a file for edit from the command line under Windows?

Mainly I am looking to open the file in the default editor associated for it (not to be confused with default action for this filetype).

This is different than just "executing" the file, so start filename is not a solution.

Note: this would require to use ShellExecute in one way or another.

Update: I added Python as an alternative to batch.

sorin
  • 161,544
  • 178
  • 535
  • 806
  • 1
    Excuse me. The default editor associated for a file is exactly the same as the default action for its filetype (_default_ is the key word here). If you want to `edit` a file from the command line then type `edit filename.txt` that open the **EDIT** file editor, that is the only MS-DOS command-line text-oriented type editor included with Windows. PS - I don't understand why people gives upvotes to a question that they don't even understand! – Aacini Nov 02 '11 at 07:49
  • 4
    @aacini Maybe you are the one not understanding the question, this has nothing to do with the ancient edit DOS application. – sorin Nov 02 '11 at 11:45
  • 4
    @Aacini, the default editor on my machine for *.HTML would be notepad, whereas my default action would be to load it as a webpage in my browser. – Paul Zaczkowski Nov 02 '11 at 11:50

2 Answers2

2

Here is a sample Python script that opens a file for edit, if there is an editor assigned to its filetype.

import os
from ctypes import c_int, WINFUNCTYPE, windll
from ctypes.wintypes import HWND, LPCSTR, UINT
prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)

filename = "readme.txt"
os.startfile(filename, "edit")

try:
    os.startfile(filename, "edit")
except WindowsError, e:
    MessageBox(text=str(e))
sorin
  • 161,544
  • 178
  • 535
  • 806
  • Very neat find. I was assuming you'd need to find the associated editor for the file extension in the registry, then launch accordingly, which sounds like a disaster. Good to see there's a much easier alternative, if I ever need it :D – Paul Zaczkowski Nov 02 '11 at 12:01
  • I have and extended version that knows to open the files in your IDE and I will publish it sooner. – sorin Nov 02 '11 at 23:02
  • Thanks a lot. I think this line is redundant `os.startfile(filename, "edit")` and you forgot `as` before `e` – YasserKhalil Mar 25 '22 at 23:25
0

64 bit Windows does not support edit command. https://www.computerhope.com/issues/ch001303.htm

To open file in with default associated app, in CMD use start <<file_path>> Reference: How to open file with default application in cmd?

To open a file in notepad, in CMD use notepad <<file_path>> in CMD

  • if file is not associated with default app to open - error will be displayed
rajkrish06
  • 39
  • 5