我正在制作一个 python 桌面应用程序,它将日志保存为 Windows 上用户的 Documents 文件夹中的 .csv 文件。该应用程序使用 python 2.7 和 kivy 1.8.0 编写,使用 pyinstaller 2.1 打包为 Windows 程序,安装程序使用 Inno Setup Compiler 制作。在这篇文章中,我将用户的真实姓名替换为 USER。
我有以下几行代码:
DOCUMENTS = os.path.expanduser('~\\Documents\\')
print DOCUMENTS
with open(DOCUMENTS + 'data_log.csv', 'ab') as f:
do stuff
Run Code Online (Sandbox Code Playgroud)
在我的电脑和我测试过的另一台电脑上,该程序按预期工作。DOCUMENTS 评估为“C:\Users\USER\Documents\”。但是,在我尝试过的其他三台计算机上,DOCUMENTS 评估为“C:\Users\USER\AppData\Roaming\SPB_16.6\Documents\”。然后程序在尝试创建 data_log.csv 时崩溃,给出以下错误:
IOError: [Errno 2] No such file or directory: 'C:\\Users\\USER\\AppData\Roaming\\SPB_16.6\\Documents\\data_log.csv'
Run Code Online (Sandbox Code Playgroud)
首先,为什么 os.path.expanduser 在某些系统上可能会行为不端,而在其他系统上却不会?
其次,即使它在错误的目录中,如果文件不存在,open() 也应该创建该文件,那么为什么会导致它崩溃呢?
我已经弄清楚是什么导致了这个问题。在大多数系统上,HOME 为 None,因此 os.path.expanduser 使用 USERPROFILE。但是,在极少数情况下,HOME 设置为 C:\SPB\ 或 C:\Users\USER\AppData\Roaming\SPB_16.6 之类的内容。我的解决方案是使用 os.environ 直接访问 USERPROFILE,而不是使用 os.path.expanduser。