Python可读取文件但无法用open()打开记事本求助(Python3.6/Win7)
open()打开记事本显示文件的问题 Hey there! Let's break down what's going on here and fix your issue.
First off, let's clarify a key point: Python's open() function doesn't automatically launch Notepad (or any external program) to display your file. All it does is create a file object that lets you read/write content from/to the file—your ability to print the file content confirms that part is working perfectly.
If you want to open the file in Notepad like you could before, you need to explicitly tell Windows to launch the program and open your file. Here are two reliable ways to do that:
方法1:使用os.startfile()(简单直接,用系统默认程序)
This method uses Windows' built-in functionality to open the file with its default associated program (which is Notepad for .txt files on Windows 7):
import os filename = "C:/Users/Eman-Win10/Desktop/Python_Images/test1.txt" # 先读取文件内容(如果需要保留这个步骤) with open(filename) as fo: print(fo.read()) # 调用系统默认程序打开文件(会自动用记事本打开txt) os.startfile(filename)
方法2:使用subprocess(强制指定记事本,更灵活)
If you want to make sure it always opens in Notepad (even if your default .txt program was changed), use the subprocess module to call notepad.exe directly:
import subprocess filename = "C:/Users/Eman-Win10/Desktop/Python_Images/test1.txt" # 读取文件内容 with open(filename) as fo: print(fo.read()) # 强制用记事本打开文件 subprocess.run(["notepad.exe", filename])
为什么之前能正常打开记事本?
Chances are, your original code included one of these system call methods (or something similar) that you might have removed accidentally. The open() function itself never had the ability to launch Notepad—you were relying on extra code to handle that part.
内容的提问来源于stack exchange,提问作者Eman4real

