【问题标题】:How to run python scripts from path while including extra files like .txt如何从路径运行 python 脚本,同时包含 .txt 等额外文件
【发布时间】:2019-08-07 08:25:22
【问题描述】:

我目前正在编写一个脚本,该脚本允许您输入 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()

【问题讨论】:

    标签: python file path file-location


    【解决方案1】:

    你可以先检查文件是否存在:

    import os
    path_exists = os.path.isdir("###your_dir###")
    file_exists = os.path.exists("text.txt")
    

    【讨论】:

    • 嗯,我可以清楚地看到文件资源管理器中有text.txt,但是返回值为False?任何原因
    • 您确定该文件在您的脚本访问的目录中吗? os.getcwd() 带给你什么?
    • 'C:\\WINDOWS\\system32',我将如何允许 python 和/或 CMD 访问输入的路径
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多