如何在Python中将打开的文件夹保存到文件中?

2024-09-22 16:33:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个应用程序,它通过askdirectory打开一个文件夹,并显示在GUI的一个输入框中,我的问题是如何将打开的文件夹保存到文件中,并在程序重新打开时再次调用它?在

我的代码:

import os
from tkinter import *
from tkinter import filedialog

inPut_dir = ''

def inPut():
    opendir = filedialog.askdirectory(parent=root,initialdir="/",title='Input Folder')
    inPut_dir = StringVar()
    inPut_dir = os.path.abspath(opendir)
    entry.delete(0, END)
    entry.insert(0, inPut_dir)

root = Tk()
root.geometry("640x240")
root.title("Settings")

frametop = Frame(root)
framebottom = Frame(root)
frameright = Frame(framebottom)

text = Label(frametop, text="Input Folder").grid(row=5, column=2)
entry = Entry(frametop, width=50, textvariable=inPut_dir)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)

ButtonA = Button(frametop, text="Change", command=inPut).grid(row=5, column=28)
ButtonB = Button(frameright, text="OK").grid(row=5, column=20, padx=10)
ButtonC = Button(frameright, text="Cancel").grid(row=5, column=15)

frametop.pack(side=TOP, fill=BOTH, expand=1)
framebottom.pack(side=BOTTOM, fill=BOTH, expand=1)
frameright.pack(side=RIGHT)

root.mainloop()

Tags: textimportinputdircolumnbuttonrootframe
2条回答

您可以使用open()函数。在

您可以定义包装器函数,例如:

def save_to_file(filename, string):
    with open(filename,'w') as out_file:
        out_file.write(string)

def read_from_file(filename):
    _dir = ''
    with open(filename) as in_file:
        _dir = in_file.read()
    return _dir

{{cd2>要保存一个名为^ cd2>的变量:

^{pr2}$

以后从文件读取:

out_dir = read_from_file(FILENAME)

试试这个:

import os
from tkinter import *
from tkinter import filedialog

def inPut():
    opendir = filedialog.askdirectory(parent=root,initialdir="/",title='Input Folder')
    inPut_dir.set (os.path.abspath (opendir))

root = Tk()
root.geometry("640x240")
root.title("Settings")

frametop = Frame(root)
framebottom = Frame(root)
frameright = Frame(framebottom)

inPut_dir = StringVar ()
text = Label(frametop, text="Input Folder").grid(row=5, column=2)
entry = Entry(frametop, width=50, textvariable=inPut_dir)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)

if os.path.isfile ("path.txt"):
    with open ("path.txt") as f: inPut_dir.set (f.read ())
else: inPut_dir.set ("")

ButtonA = Button(frametop, text="Change", command=inPut).grid(row=5, column=28)
ButtonB = Button(frameright, text="OK").grid(row=5, column=20, padx=10)
ButtonC = Button(frameright, text="Cancel").grid(row=5, column=15)

frametop.pack(side=TOP, fill=BOTH, expand=1)
framebottom.pack(side=BOTTOM, fill=BOTH, expand=1)
frameright.pack(side=RIGHT)

root.mainloop ()

with open ("path.txt", "w") as f: f.write (inPut_dir.get ())

编辑:

如果您对选择多个目录感兴趣,您可以查看另一个stack overflow问题的this链接。在

相关问题 更多 >