简体   繁体   中英

Python join filepath and filename

I am browsing for a file which works fine:

def fileDialog(self):
    self.filename = filedialog.askopenfilename(initialdir = "/", title = "Select file", filetypes = 
    (("excel files","*.xl*"),("all files","*.*")))
self.uploadRoster()

By selection that particular excel file, I can convert the excel file into database; however, the database is created in same location but I want to copy the database to the directory where my script is saved or some other desired folder but this won't work.

def uploadRoster(self):
    response = messagebox.askquestion(title = "Upload Roster", message = "Do you wish to continue?")
    if response == 'yes':
        excel_file = self.filename
        connection = sqlite3.connect(os.path.splitext(excel_file)[0] + ".db")
        wb = pd.read_excel(excel_file, sheet_name = [0])
        for sheet in wb:
            wb[sheet].to_sql("employee_details", connection, index=False, if_exists = 'append')
        connection.commit()
        connection.close()
    elif response == 'no':
        pass

Above will convert the file(example "Roster.xlxs to "Roster.db") but this should be saved in other directory because later I don't have access to the location of "Roster.xlxs" path.... Any help will be really appreciated

You can set the new path for your database at these lines;

# ... logic ....
if response == 'yes':
    excel_file = self.filename
    connection = sqlite3.connect(os.path.splitext(excel_file)[0] + ".db")
# .... logic 

For example;

def uploadRoster(self):
    response = messagebox.askquestion(title = "Upload Roster", message = "Do you wish to continue?")
    if response == 'yes':
        excel_file = self.filename

        # extract the name 
        name = os.path.splitext(excel_file)[0]

        # create new path for your db 
        # you may want to use os.path.join() here
        path = 'path_to/your_folder/' + name + '.db' 

        # create db at specified path
        connection = sqlite3.connect(path)

        wb = pd.read_excel(excel_file, sheet_name = [0])
        for sheet in wb:
            wb[sheet].to_sql("employee_details", connection, index=False, if_exists = 'append')

        connection.commit()
        connection.close()

    elif response == 'no':
        pass

From the Docs: https://docs.python.org/3/library/sqlite3.html

import sqlite3
dbdir='C:\\Temp\\SQL\\' #put your path here
conn = sqlite3.connect(dbdir+'example.db')

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