简体   繁体   中英

How to write a program that references to file, where the directory changes

I'm currently working on a program that uses databases and all that kind of stuff for a friend of mine. Now while doing my basic planning of what I will need to do, I thought to myself how will I get the program to connect to the right MS Access database if I hard code the path to my own personal computer? Because ill be using pyinstaller to package the program for him.

Do I need to build the directory in a dynamic way that uses the path of the current script, and then some string manipulation of that path to get the right file? ie

import os
    
file_path = os.path.realpath(__file__)
# Using prior knowledge knowing the file name length is 7
file_path = file_path[:-7]                        
#appending the path string to point to the database
file_path = file_path + "/databases/test.accdb"   

Or will the program still someway find its way to that database?

You can use a: os.walk(...) function to locate specified name file or every database file in specified directories. Next user can choose which file is correct

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