Python 从.txt文件加载,无文件目录

Python 从.txt文件加载,无文件目录,python,load,tkinter,save,Python,Load,Tkinter,Save,当我运行这段代码时,我得到一个错误,说文件不存在,我已经创建了文件,并通过从保存部分复制目录链接回它们。我也可以看到该文件,并已三次检查的名称等,但它仍然不会工作,可以有人帮助 from tkinter import * import os.path master= Tk() master.geometry('500x500+0+0') def print_value(val): print ("c1="+str (c1v.get())) print ("c2="+str(

当我运行这段代码时,我得到一个错误,说文件不存在,我已经创建了文件,并通过从保存部分复制目录链接回它们。我也可以看到该文件,并已三次检查的名称等,但它仍然不会工作,可以有人帮助

from tkinter import *
import os.path
master= Tk()
master.geometry('500x500+0+0')



def print_value(val):
    print ("c1="+str (c1v.get()))
    print ("c2="+str(c2v.get()))


c1v=DoubleVar()
c2v=DoubleVar()


c1 = Scale(master, from_=255, to=0, length =400,width =100, troughcolor = 'blue',command=print_value, variable =c1v)
c1.grid(row=1,column=1)
c2 = Scale(master, from_=255, to=0, length =400,width =100, troughcolor = 'blue',command=print_value, variable =c2v)
c2.grid(row=1,column=2)


def func():
    pass
    file1 = open("C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt")
    val1, val2 = (x.split("=")[1] for x in file1)
    c1.set(val1)
    c2.set(val2)
    file1.close()


def record():

    save_path = 'C:/Users/Josh Bailey/Desktop/pi_dmx'
    name_of_file = ("preset_test ")
    completeName = os.path.join(save_path, name_of_file+".txt")
    file1 = open(completeName , "w")
    toFile = ("c1="+str (c1.get())+ "\n""c2="+str(c2.get()))
    file1.write(toFile)
    file1.close()
    master.mainloop()

rec=Button(master, text="Record",width=20, height=10, bg='Red', command=record)
rec.grid(row=2, column=1)

load=Button(master, text="Load",width=20, height=10, bg='gold',command=func)
load.grid(row=2, column=2)
错误是-

Exception in Tkinter callback Traceback (most recent call last):  
 File "C:\Python33\lib\idlelib\run.py", line 121, in main
     seq, request = rpc.request_queue.get(block=True, timeout=0.05)   File "C:\Python33\lib\queue.py", line 175, in get
     raise Empty queue.Empty

During handling of the above exception, another exception occurred:

 Traceback (most recent call last):   File
 "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
     return self.func(*args)   File "C:\Users\Josh Bailey\Desktop\save test.py", line 24, in func
     file1 = open("C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt") FileNotFoundError: [Errno 2]
No such file or directory: 'C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt'

你在Windows上,对吗?将斜杠替换为反斜杠,\,并在字符串前面添加一个“r”,如下所示:

file1 = open(r"C:\Users\Josh Bailey\Desktop\pi_dmx\preset_test.txt")

希望这能在
func
中起作用,您可以将文件路径指定为:

C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt
但是,您的
记录功能使其成为:

C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test .txt
#                   Note the extra space here--^
因此,Python将无法找到该文件


要解决此问题,请在
记录中删除此行上的空格

name_of_file = ("preset_test ")
#                     here--^
现在record将创建它应该创建的文件路径



而且,
func
内部的
pass
不应该存在。它什么也不做。

实际上,Python可以在Windows上使用带有正斜杠的文件路径。非常好,谢谢,是的,我在前面添加int时忘了删除pass