简体   繁体   中英

python pandas dataframe to_sql : how to set up sqlite db file created directory

conn = sqlite3.connect('test.db')
essential_df.to_sql('collection',conn, if_exists='append')
conn.close

I'm currently working on kind of a db collector from some website. I want to download excel file from the website and want to modify the data as I want and want to store it into database which I chose to be sqlite.

I successed to download the excelfile with selenium and finally I modified the data as I want with pandas. the data is stored as a pandas dataframe.

As I wanted to store this into db, I tried to work with cursor() and execute method but kept failed. so I chose to use pandas to_sql method. and it worked with if_exists='append' method as I wanted.

============Here comes my real question!============

when I worked with data sotring only with pandas, the db file is saved at the .py file located directory. however, when I added selenium function into the code, it strangely began to create file into the download folder of windows, where excel file is downloaded. is there anyone why it happened?and can guide me how to save the db file into current directory(where .py file located)?

When you are running your code via py file, the current working directory will be the directory where py file is present.

However, it seems to get changed after adding selenium code.

The current working directory for both case can be checked using os.getcwd().

Solution:

Add below code in py file.

>>> a=os.path.join(os.getcwd(),'test.db')
>>> a
'C:\\Users\\punddin\\test.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