简体   繁体   中英

Pass file data between functions

In the abridged code that follows, I am going to obtain (a lot of) data from a file within the function OpenFile, and I want to use the data in another function, ss, without having to read the data from the file again. Is this possible and if so, how do I do it? I think it is equivalent to passing a variable between functions, but I cannot seem to get my head around that or how to apply it in this case. In advance, I am grateful for your assistance as well as your patience with my novice skills.

<3

from Tkinter import *
from tkFileDialog   import askopenfilename, asksaveasfile

def OpenFile():

    gen = []
    fam = []
    OTUs = []

    save_fam = []
    save_gen = []
    save_OTU = []

    FindIT_name = askopenfilename()
    data = open(FindIT_name, "r").readlines()

    #some data manipulation here


def ss():
    ss_file = asksaveasfile(mode="w", defaultextension=".csv")
    ss_file.write("OTU, Family, Genus")
    #I want to get data here, specifically data from FindIT_name (see OpenFile function) 

root = Tk()
root.minsize(500,500)
root.geometry("500x500")
root.wm_title("Curate Digitized Names")

menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Get FindIt Input", command=OpenFile)
filemenu.add_separator()
filemenu.add_command(label="Quit", command=stop)
menubar.add_cascade(label="File", menu=filemenu)

root.config(menu=menubar)
root.mainloop()

To be honest, that was too much code for me to really read through, but in general the way you'd want to pass the data between functions would be like this:

def foo(file_path):
    data = open(file_path, 'rb').read()
    result = bar(data)

def bar(data):
    ### do something to data

For applying to your original example something like this would work:

def OpenFile():

gen = []
fam = []
OTUs = []

save_fam = []
save_gen = []
save_OTU = []

FindIT_name = askopenfilename()
ss(FindIT_name)
data = open(FindIT_name, "r").readlines()

#some data manipulation here


def ss(FindIT_name):
    ss_file = asksaveasfile(mode="w", defaultextension=".csv")
    ss_file.write("OTU, Family, Genus")
    ### If you need to do something, you now have FindIT_name available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM