How to write a portable program in python that accesses particular directories?

StackOverflow https://stackoverflow.com/questions/18178664

  •  24-06-2022
  •  | 
  •  

문제

I have a python program that I've written that requires a specific database that is located in a folder on my computer directory.

Currently my program initializes the database in the same location as where the python script is found, and I thought this is the best way to do it so that the database stays 'static' relative to the script.

My question is, is there a different way of doing this? Perhaps some kind of best practice? Also, what exactly is this concept called?

This is my first time to write a program for other people to use and I'm a bit nervous that it might break somewhere.

도움이 되었습니까?

해결책

I would use the user's home folder and use the os.path module. Let's say you have a program named myapp and a database called db.sqlite.

import os.path
path = os.path.expanduser('~/.myapp/db.sqlite')

path would then be expanded to /home/user/.myapp/db.sqlite on a UNIX-based system (and similar for Mac) and C:\Users\user\Application Data\Roaming.myapp\db.sqlite (or something similar, not on a windows machine) on a Windows machine.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top