-5

I'm trying to open a file via my python project, but it doesn't work.. Is there any reason why?


import os
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk,Image

def openfile():

   window.filename = filedialog.askopenfilename(initialdir="Open file", filetypes=(("exe files", "*.exe"),("all files", "*.*"))
    file_opener = open(window.filename)
    file_opener.read()

Button = Button(window, text="Open", command=openfile)
Button.pack()

Woo
  • 1
  • 2

1 Answers1

1

This code below just gets the content of the file.

import os
from tkinter import *
from tkinter.filedialog import *


window = Tk()

def openfile():
    window.filename = askopenfilename(title="Open file",
                                      filetypes=(("exe files", "*.exe"),
                                      ("all files", "*.*")))
    data = ""
    try:
        with open(window.filename) as f:
            data = f.read()
    except:
        pass

Button = Button(window, text="Open", command=openfile)
Button.pack()

The line

data = f.read()

Stores the content of the file in data. That’s all.
Then, if you want to run this file, you can do this:

1. Use os

If you want to open / run the .exe file, use os.system like that:

import os
os.system(window.filename)

This code acts like, for example on Windows, if you open a command prompt and type [the file path] -- It runs the file

2. Use subprocess

According to Brian, you can type this to run filename:

import subprocess
subprocess.call(filename)

You can also go to this page (possible duplicate)

D_00
  • 1,440
  • 2
  • 13
  • 32