繁体   English   中英

如何在python中用记事本打开其他扩展名的文件

[英]How to open a file of different extension with notepad in python

我有一个.fhx文件,可以用记事本正常打开它,但是我想用Python打开它。 我已经试过上线的subprocess.popen,但是一直出错。 我还希望能够像普通文本文件一样读取此文件的内容,就像我们在f = open(“ blah.txt”,“ r”)和f.read()中所做的一样。 谁能指导我正确的方向?

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

尝试使用shell=True参数subprocess.call(((notePath,filepath),shell = True)

通过在文件打开命令中添加encoding =“ utf16”解决了我的问题。

    count = 1
    filename = r'C:\Users\Ch\Desktop\FHX\27-ESDC_CM02-2.fhx'
    f = open(filename, "r", encoding="utf16") #Does not work without encoding
    lines = f.read().splitlines()
    for line in lines:
        if "WIRE SOURCE" in line:
            liner = line.split()
            if any('SOURCE="INPUT' in s for s in liner):
                print(str(count)+") ", "SERIAL INPUT = ", liner[2].replace("DESTINATION=", ""))
            count += 1

现在我可以按自己想要的方式获取数据了。谢谢大家。

您应该传递一个args列表:

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

如果您想阅读内容,则使用open打开文件:

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

您需要使用原始字符串的路径也逃脱f n您的文件路径名,如果不这样做,你会得到错误。

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM