【问题标题】:I'm trying to open a file via python我正在尝试通过 python 打开一个文件
【发布时间】:2020-06-05 22:20:48
【问题描述】:

我试图通过我的 python 项目打开一个文件,但它不起作用.. 有什么原因吗?


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()

【问题讨论】:

标签: python button tkinter


【解决方案1】:

下面这段代码只是获取文件的内容。

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()

线

data = f.read()

将文件的内容存储在data 中。就是这样。
然后,如果你想运行这个文件,你可以这样做:

1。使用os

如果要打开/运行.exe 文件,请像这样使用os.system

import os
os.system(window.filename)

此代码的作用类似于,例如在 Windows 上,如果您打开命令提示符并键入 [the file path] -- 它会运行该文件

2。使用subprocess

根据Brian,你可以输入这个来运行filename

import subprocess
subprocess.call(filename)

你也可以去this page(可能重复)

【讨论】:

    猜你喜欢
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多