简体   繁体   中英

Python open a text(notepad) document

Im new at programming and i was wondering how can i open a notepad document so the user can type on it. I already know that you can use

variablename  = open("filename.txt","w")

to open and write on a file but instead of writing on python i wanted the file to open directly so the user can type on the actual file not in python shell. So far i know that i have to use

import os
os.?????(filename.txt)

but i dont know how to make the file pop up so the user can enter data. can somebody help me?

This easiest approach using os is to use os.system to run a shell script:

import os
os.system("notepad filename.txt")

Or using subprocess.Popen which is usually the recommended way:

import subprocess
subprocess.Popen(["notepad","filename.txt"])
# the concepts of both my methods is they run a shell script calling notepad to run filename.txt

But I believe only Windows has the Notepad application.

You can also use the suggested method from the comments:

import subprocess
subprocess.run(["notepad","filename.txt"])

But that only works in Python 3.5+

import os
os.system("start notepad.exe <path/to/file>")

This will pop-up Notepad. If the file doesn't exist, there will be a prompt asking if you'd like to create it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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