How to open a file in its default program with python

前端 未结 3 1841
甜味超标
甜味超标 2020-12-21 16:51

I want to open a file in python 3.5 in its default application, specifically \'screen.txt\' in Notepad.

I have searched the internet, and found os.startfile(pa

相关标签:
3条回答
  • 2020-12-21 16:59

    The recommended way to open a file with the default program is os.startfile. You can do something a bit more manual using os.system or subprocess though:

    os.system(r'start ' + path_to_file')
    

    or

    subprocess.Popen('{start} {path}'.format(
        start='start', path=path_to_file), shell=True)
    

    Of course, this won't work cross-platform, but it might be enough for your use case.

    0 讨论(0)
  • 2020-12-21 17:01

    It's hard to be certain from your question as it stands, but I bet your problem is backslashes.

    [EDITED to add:] Or actually maybe it's something simpler. Did you put quotes around your pathname at all? If not, that will certainly not work -- but once you do, you will find that then you need the rest of what I've written below.

    In a Windows filesystem, the backslash \ is the standard way to separate directories.

    In a Python string literal, the backslash \ is used for putting things into the string that would otherwise be difficult to enter. For instance, if you are writing a single-quoted string and you want a single quote in it, you can do this: 'don\'t'. Or if you want a newline character, you can do this: 'First line.\nSecond line.'

    So if you take a Windows pathname and plug it into Python like this:

    os.startfile('C:\foo\bar\baz')
    

    then the string actually passed to os.startfile will not contain those backslashes; it will contain a form-feed character (from the \f) and two backspace characters (from the \bs), which is not what you want at all.

    You can deal with this in three ways.

    • You can use forward slashes instead of backslashes. Although Windows prefers backslashes in its user interface, forward slashes work too, and they don't have special meaning in Python string literals.

    • You can "escape" the backslashes: two backslashes in a row mean an actual backslash. os.startfile('C:\\foo\\bar\\baz')

    • You can use a "raw string literal". Put an r before the opening single or double quotes. This will make backslashes not get interpreted specially. os.startfile(r'C:\foo\bar\baz')

    The last is maybe the nicest, except for one annoying quirk: backslash-quote is still special in a raw string literal so that you can still say 'don\'t', which means you can't end a raw string literal with a backslash.

    0 讨论(0)
  • 2020-12-21 17:11

    For example I created file "test file.txt" on my drive D: so file path is 'D:/test file.txt' Now I can open it with associated program with that script:

    import os
    os.startfile('d:/test file.txt')
    
    0 讨论(0)
提交回复
热议问题