我有一个python脚本,其中我将工作目录Directory_1
定义为硬编码字符串。如果计算机中不存在该文件,则会提示您选择其他目录Directory_2
。 Directory_2
应该替换目录。
要求:如果目录不存在,请替换硬编码并将其存储在内存中,直到选定的目录存在于计算机中为止,以便下次运行。对于相同脚本的多次运行,我应该怎么做来存储用户选择目录。
#Python
directory_1=r'C:/Users/XX/Weekly_report_generator/DTR_Py_REC'
exist=os.path.isdir(directory_1)
if not exist:
import tkinter
from tkinter import filedialog
from tkinter import *
window=Tk()
directory_2 = filedialog.askdirectory()
directory_1=directory_2
mainloop()
print(directory_1)
答案 0 :(得分:0)
这是在文件中保存路径的示例,因此用户不必在每次运行程序时都指定路径:
from os.path import expanduser
def main():
# The path to try first if the user hasn't specified a directory
path = '/my/default/path'
# Compute the path where we save the user's directory choice
savedDirFile = expanduser("~/.report_gen_saved_dir")
if os.path.exists(savedDirFile):
# If we've saved a path away that the user specified in another run, load that path from file
with open(savedDirFile) as f:
path = f.read()
elif not os.path.isdir(path):
# Otherwise, if the default path isn't a valid directory, prompt the user for a directory
# @@@ user interaction code here @@@
path = '/some/user/selected/path' # Do your thing here to have the user specify a directory
# Save off the user's directory choice for future runs
with open(savedDirFile, "w") as f:
f.write(path)
print(path)
main()
这会将所选目录保存在用户主目录中名为 .report_gen_saved_dir 的文件中。