如何存储Python应用程序数据
我正在创建一个简单的Python CLI工具,该工具可让用户添加和删除任务(经典的Todo应用程序).这仅供我自己使用,但是我想了解创建此类应用程序的最佳实践.数据将存储在一个简单的文本文件中.
I'm creating a simple Python CLI tool, which lets the user add and delete tasks (the classic Todo app). This is just for my own use, but I want to get into the best practices of creating such applications. The data will be stored in a simple text file.
主要问题:我应该将数据文件存储在哪里?在完成一些阅读之后,倾向于在/var/lib
中创建一个新文件夹,并将data.txt
文件保留在该目录中.该选项有什么缺点吗?
Main question: Where should I store the data file? After doing some reading, I'm inclined to create a new folder in /var/lib
and keep the data.txt
file in that directory. Are there any drawbacks to that option?
后续问题:由于默认情况下,只有超级用户才能访问/var
,因此我是否需要更改整个/var
目录的权限才能读取和写入数据文件?
Follow up question: Since, by default, only root has access to /var
, do I need to change the permissions for the whole /var
directory in order to read and write to the data file?
用户数据应存储在用户的主目录中.您可以使用
User data should be store in the user's home directory. You could use
/Users/joe/.myclitool/data.txt
在Mac OS X和
/home/joe/.myclitool/data.txt
在GNU/Linux下.
under GNU/Linux.
在Python中,这可以通过
In Python this can be done with
import os
import os.path
p = os.path.join(os.getenv("HOME"), ".myclitool", "data.txt")