How to open a different extension file with notepad in python

advertisements

I have a .fhx file that I could open normally with notepad but I want to open it using Python. I have tried subprocess.popen which I got online but I keep getting errors. I also want to be able to read the contents of this file like a normal text file like how we do in f=open("blah.txt", "r") and f.read(). Could anyone guide me in the right direction ?

    import subprocess
    filepath = "C:\Users\Ch\Desktop\FHX\fddd.fhx"
    notePath = r'C:\Windows\System32\notepad.exe'
    subprocess.Popen("%s %s" % (notePath, filepath))


You should be passing a list of args:

import subprocess
filepath = r"C:\Users\Ch\Desktop\FHX\fddd.fhx"
notePath = r'C:\Windows\System32\notepad.exe'
subprocess.check_call([notePath, filepath])

If you want to read the contents then just open the file using open:

with open(r"C:\Users\Ch\Desktop\FHX\fddd.fhx") as f:
     for line in f:
        print(line)

You need to use raw string for the path also to escape the f n your file path name, if you don't you are going to get errors.

In [1]: "C:\Users\Ch\Desktop\FHX\fddd.fhx"
Out[1]: 'C:\\Users\\Ch\\Desktop\\FHX\x0cddd.fhx'

In [2]: r"C:\Users\Ch\Desktop\FHX\fddd.fhx"
Out[2]: 'C:\\Users\\Ch\\Desktop\\FHX\\fddd.fhx'