将返回值用作变量,而无需调用整个函数

时间:2019-02-27 01:16:28

标签: python python-3.x csv tkinter

这是我的目标:

创建一个接受2个CSV文件并返回仅包含差异的第3个CSV文件的脚本。

我正在使用Python 3.7.2。

这是我的代码:

def findFile1():
    filename =  ## prompts the user to select a .csv file.
    with open(filename, 'r') as t1:
        fileone = t1.readlines()
    return fileone


def findFile2():
    filename =  ## prompts the user to select another .csv file.
    with open(filename, 'r') as t2:
        filetwo = t2.readlines()
    return filetwo


def saveFile():
    filename =  ## prompts the user to name and choose a location to save a new .csv file.
    fileone = findFile1() ##Here I would just like to readlines from the first CSV file. Not run the whole script again. 
    filetwo = findFile2() ##Here I would just like to readlines from the second CSV file. Not run the whole script again.
    with open(filename, 'w') as outFile:
        for line in filetwo:
            if line not in fileone:
                outFile.write(line)

我只想使用前两个函数的返回值,而不是再次调用整个函数。

更新: 我能够用Charles Duffy的建议“导入functools并将@ functools.lru_cache()行放在函数上方,以后所有的调用将重用先前调用的结果”来解决此问题。

2 个答案:

答案 0 :(得分:0)

没有足够的信息,我在这里做一些猜测: 我也不熟悉tkinter:

这是一些有关通过Button将参数传递给函数的帮助的链接 How to pass arguments to a Button command in Tkinter?

from tkinter import filedialog
from tkinter import messagebox
from tkinter import *

master = Tk()

def findFile1():
    master.filename =  filedialog.askopenfilename(initialdir = "C:/",title = "Select file 1",filetypes = (("CSV","*.csv"),("all files","*.*")))
    print (master.filename)
    with open(master.filename, 'r') as t1:
        fileone = t1.readlines()
    return fileone


def findFile2():
    master.filename =  filedialog.askopenfilename(initialdir = "C:/",title = "Select file 2",filetypes = (("CSV","*.csv"),("all files","*.*")))
    print (master.filename)
    with open(master.filename, 'r') as t2:
        filetwo = t2.readlines()
    return filetwo


def saveFile(fileone, filetwo):
    master.filename =  filedialog.asksaveasfilename(initialdir = "C:/",title = "Save file",filetypes = (("CSV","*.csv"),("all files","*.*")))
    print (master.filename)
    with open(master.filename, 'w') as outFile:
        for line in filetwo:
            if line not in fileone:
                outFile.write(','.join(line.split()))
    messagebox.showinfo("Sucess", "File created successfully!")


file1 = Button(master, text="Load file 1", command=findFile1)
file1.pack()

file2 = Button(master, text="Load file 2", command=findFile2)
file2.pack()

start = Button(master, text="START", command=saveFile)
start.pack()

master.geometry("300x300")

mainloop()

答案 1 :(得分:0)

更新:我能够用Charles Duffy的建议“导入functools并将@ functools.lru_cache()行放在函数上方,以后所有的调用将重用先前调用的结果”来解决此问题