I have a function open_data
that opens a file dialog for me to select a specific file. I want to access the selected file in another function run_data
within the same file. Below is a sample demonstration of my code. Any suggestions to the selected file in the run_data
function are welcomed.
def open_data():
dialog = filedialog.askopenfilename(initialdir=".\", title="Select A Data",
filetypes=(("numpy files", "*.npy"),
("all files", "*.*")))
for data in dialog:
print(data, end="")
def run_data():
## I want to access the selected data from the above dialog in this function##
return data
CodePudding user response:
askopenfilename()
returns a file name not an open file, so you will need to open it in order to be able to access its contents. You also need to check because the value returned can be None
if the user canceled the dialog without selecting anything.
Since you want to retrieve the data in a separate function, you will need to use a global
variable to hold the data between function calls.
data = None # Initialize global variable.
def open_data():
global data
filename = filedialog.askopenfilename(initialdir=".\", title="Select A Data",
filetypes=(("numpy files", "*.npy"),
("all files", "*.*")))
if not filename:
data = None # User didn't select a file.
else:
data = np.load(filename)
def run_data():
return data