0

我目前正在编写一个脚本,该脚本允许您输入 python 脚本的路径并运行它,这对于运行相同类型的代码进行故障排除非常有用,因为有时程序会崩溃 CMD,您必须重新输入位置ECT的所有信息。

目前它工作得很好,但是它出现了

Traceback (most recent call last): File "E:\Coding Type of stuff\Python\Testing\test.py", line 1, in <module> print(open("text.txt","r").readlines()[0]) FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'

我知道为什么会发生这种情况的错误,但是有什么解决方法吗?

python脚本运行器的当前代码:

import tkinter as tk
from subprocess import Popen
try:
    path = (open("path.txt","r").readlines())[0]
    print(path)
except:
    path = "Enter path..."
    open("path.txt","w").write("")
def on_entry_click(event):
    if entry.get() == path:
       entry.delete(0, "end")
       entry.insert(0, '')
       entry.config(fg = 'black')
def on_focusout(event):
    if entry.get() == '':
        entry.insert(0, path)
        entry.config(fg = 'grey')
def get_input(box):
    try:
        path = box.get()
        if path != "Enter path...":
            open("path.txt","w").write(path)
            Popen('python "'+path+'"')
        else:
            print("No path entered")
    except:
        print("That path does not work")
root = tk.Tk()
root.geometry("375x50")
label = tk.Label(root, text="Path: ")
label.grid(row = 0, column = 0)
entry = tk.Entry(root, bd=1, width = 50)
entry.insert(0, path)
entry.bind('<FocusIn>', on_entry_click)
entry.bind('<FocusOut>', on_focusout)
entry.config(fg = 'grey')
button = tk.Button(root, text = "Run", command = lambda: get_input(entry))
entry.grid(row = 0, column = 1)
button.grid(row = 1)

root.mainloop()
4

1 回答 1

0

您可以先使用以下方法检查文件是否存在:

import os
path_exists = os.path.isdir("###your_dir###")
file_exists = os.path.exists("text.txt")
于 2019-08-07T08:34:23.817 回答