5

I want to open a file using the subprocess module as though the file was double-clicked in Explorer. How do I do that?

I tried the following line:

subprocess.call("C:/myfile.csv", shell=True)

which throws an error saying:

The syntax of the command is incorrect.
'C:\' is not recognized as an internal or external command, operable program or batch file.

How do I emulate a double-click using subprocess? Basically I want to open a CSV file in Excel 2007.

3
  • I think subprocess.call(r'C:\myfile.csv', shell=True) should do it (not sure, and os.startfile is cleaner). Commented Dec 14, 2010 at 2:32
  • @Chris: I actually used shell=True, forgot to include it in the question. Using shell=True would produce the error I mentioned above. Commented Dec 14, 2010 at 2:39
  • I think you missed the fact that Chris used a raw string with a backslash for his path and you didn't in yours (and the difference may be significant). Commented Dec 14, 2010 at 6:49

3 Answers 3

10
os.startfile(r'C:\myfile.csv')

(Win32 only. For Mac, run a process with 'open filename'; on Linux/freedesktop-in-general, 'xdg-open filename'.)

Sign up to request clarification or add additional context in comments.

1 Comment

+1. subprocess.call tries to run something as an executable. Your CSV file isn't an executable; it's data for one. Each platform has its own utility application for "figure out what kind of file this is and feed it to the appropriate application", which is what you're really trying to do.
1

I think part of your problem is you're using a unix style slash / as a path separator, instead of the windows backslash . It looks like windows is interpreting /myfile.csv as an argument for the program C:, which is why you're getting that message.

However if you corrected that, I think you'd just get it saying that C:\myfile.csv isn't a program.

Comments

0

I know that this is a bit late, but to do that in python 2.x (not sure about 3) you should use the subprocess module, referencing Popen. Here is the code:

import subprocess
subprocess.Popen(r'explorer /select, "C:\"')

It basically opens the file, and then opens it in the default program.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.