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()
To run a file, use os.system([file path])
. That runs the command [file path]
which runs the file.
For example, if you have a file in your desktop name test.py
, typing os.system("C:\Users\[username]\desktop\test.py")
runs the file test.py
.
There is a code which runs a file chosen by user:
from tkinter.filedialog import *
import os
path = askopenfilename()
os.system(path)
But if the path contains spaces, add the following code just before os.system(path)
:
for character in path:
if character == ' ': # space detected?
path = ('\"' # add " at the beginning
+ path # add the path
+ '\"') # add " at the end
break
print(path) # check if the path is corrected
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.