0

I am writing a text-based application in Python 3.9.9 in VSCode on MacOS.

I am trying to write some code that will allow the user the option to launch a text file in his/her default text editor. The text file is going to serve as a Help file that the user can launch from my application, and then close when they are done or work with side-by-side the application.

I want to include the text file in the same directory as the main python app file or in a nested directory and provide a relative path to it.

I don't need to read or update the file. I just need to launch it.

I think the OS module or subprocess module may be the way to go, but I'm having trouble making it work with either....

0m3r
  • 12,286
  • 15
  • 35
  • 71

2 Answers2

1

Try to check this -> Open document with default OS application in Python, both in Windows and Mac OS.


My solution

import subprocess as sp
defEditor = "notepad.exe"
#note that r is essential to read the path
path = r"C:\x\x\x\text.txt" 
sp.Popen([defEditor, path])

You can make this a bit better, by using an if statement to identify the OS of the user, to then run the correct default text-editor.

import subprocess as sp
import platform
#Check the OS
OS = platform.platform()
#Check if "Windows" is substring of OS
if "Windows" in OS:
    defEditor = "notepad.exe"
    path = r"C:\x\x\x\testo.txt"
    sp.Popen([defEditor, path])

As far as i know, using os.system is discuraged because of security reasons, but more expert users can correct my statement. Hope this helped

Viassone
  • 71
  • 5
0

Have you tried using OS Module?, The functions that the OS module provides allows you to interface with the underlying operating system that Python is running on

example

import os
os.system("file.txt")
0m3r
  • 12,286
  • 15
  • 35
  • 71