簡體   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