简体   繁体   中英

python- how to make this variable read excel file from the path i get?

I have two buttons "Browse File 2A" and "Browse File PR" which open and read the selected excel file paths, how can i make that file paths get read("open" those excel files so that my rest of the code in the save_slogan() works) by variables df1 and df2?? See my function save_slogan(), here my code:

from tkinter import *

# import filedialog module
from tkinter import filedialog
import pandas as pd
# Function for opening the
# file explorer window
from tkinter import *
import smtplib
def browseFiles1():
    filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.txt*"),
                                                       ("all files",
                                                        "*.*")))

    # Change label contents
    label_file_explorer.configure(text="File Opened: "+filename)



def browseFiles():
    filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.txt*"),
                                                       ("all files",
                                                        "*.*")))

    # Change label contents
    label_file_explorer.configure(text="File Opened: "+filename)


def save_slogan():
 import pandas as pd
df1=#read and open the excel file from its file path from function browseFiles() 
df2=#read and open the excel file from its file path from function browseFiles1()
xx1=df1.rename(columns={"Description":"Desc 2A","Doc Number":"Document Number"})
xx=df2.rename(columns={"Description":"Desc PR","Doc Number":"Document Number"})
combined = pd.merge(xx1, xx, how="outer", on="Document Number")
def case_code(row): 
    if row["Tax Amount 2A"] == row["Tax Amount PR"]:
        return "exact"
    elif pd.isna(row["Tax Amount 2A"]):
        return "Addition in PR"
    elif pd.isna(row["Tax Amount PR"]):
        return "Addition in 2A"
    elif row["Tax Amount 2A"] != row["Tax Amount PR"]:
        return "mismatch"

codes=combined.apply(case_code, axis="columns")
answer = combined.assign(**{"Match type": codes})
final=answer[["Match type"] + [*combined.columns]] 
final.to_excel('done1.xlsx')     


# Create the root window
window = Tk()

# Set window title
window.title('File Explorer')

# Set window size
window.geometry("500x500")

#Set window background color
window.config(background = "white")

# Create a File Explorer label
label_file_explorer = Label(window,
                            text = "PR2A",
                            width = 100, height = 4,
                            fg = "blue")


button_explore = Button(window,
                        text = "Browse File 2A",
                        command = browseFiles)
button_explore1 = Button(window,
                        text = "Browse File PR",
                        command = browseFiles1)
button_explore2 = Button(window,
                        text = "Go and Save",
                        command = save_slogan)




# the widgets at respective positions
# in a table like structure by
# specifying rows and columns
label_file_explorer.grid(column = 1, row = 1)

button_explore.grid(column = 1, row = 2)
button_explore1.grid(column=1, row=3)
button_explore2.grid(column=1,row=4)



# Let the window wait for any events
window.mainloop()

pls help

You need to store the selected files. Since you need to know whether the selected file is for "2A" or "PR", suggest to use a dictionary to store the selected files.

You can combine the two browseFiles functions into one and pass the required file type as an argument:

# dictionary to store the selected files
selected_files = {"2A": None, "PR": None}

def browseFile(ftype):
    filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("Excel files",
                                                        "*.xlsx"),
                                                       ("all files",
                                                        "*.*")))
    if filename:
        # a file is selected, so store the selected file
        selected_files[ftype] = filename
        # Change label contents
        txt = "\n".join(f"{ftype}: {fname}" for ftype, fname in selected_files.items())
        label_file_explorer.configure(text="File Opened:\n"+txt)

def save_slogan():
    import pandas as pd
    # check whether required files are selected
    if all(selected_files.values()):
        df1=pd.read_excel(selected_files["2A"])
        df2=pd.read_excel(selected_files["PR"])
        xx1=df1.rename(columns={"Description":"Desc 2A","Doc Number":"Document Number"})
        xx=df2.rename(columns={"Description":"Desc PR","Doc Number":"Document Number"})
        combined = pd.merge(xx1, xx, how="outer", on="Document Number")

        def case_code(row):
            if row["Tax Amount 2A"] == row["Tax Amount PR"]:
                return "exact"
            elif pd.isna(row["Tax Amount 2A"]):
                return "Addition in PR"
            elif pd.isna(row["Tax Amount PR"]):
                return "Addition in 2A"
            elif row["Tax Amount 2A"] != row["Tax Amount PR"]:
                return "mismatch"

        codes=combined.apply(case_code, axis="columns")
        answer = combined.assign(**{"Match type": codes})
        final=answer[["Match type"] + [*combined.columns]]
        final.to_excel('done1.xlsx')

Then change the command option of the two buttons as below:

button_explore = Button(window,
                        text = "Browse File 2A",
                        command = lambda: browseFile("2A"))
button_explore1 = Button(window,
                        text = "Browse File PR",
                        command = lambda: browseFile("PR"))

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