Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a file depending on the user Python

Tags:

python

I try to write a script in Python that saves the file in each user directory. Example for user 1, 2 and 3.

C:\Users\user1\Documents\ArcGIS\file1.gdb

C:\Users\user2\Documents\ArcGIS\file1.gdb

C:\Users\user3\Documents\ArcGIS\file1.gdb

How can I do this?

like image 814
CesarD Avatar asked Jul 25 '13 16:07

CesarD


2 Answers

As one commenter pointed out, the simplest solution is to use the USERPROFILE environment variable to write the file path. This would look something like:

import os
userprofile = os.environ['USERPROFILE']
path = os.path.join(userprofile, 'Documents', 'ArcGIS', 'file1.gdb')

Or even more simply (with better platform-independence, as this will work on Mac OSX/Linux, too; credit to Abhijit's answer below):

import os
path = os.path.join(os.path.expanduser('~'), 'Documents', 'ArcGIS', 'file1.gdb')

Both of the above may have some portability issues across Windows versions, since Microsoft has been known to change the name of the "Documents" folder back and forth from "My Documents".

If you want a Windows-portable way to get the "Documents" folder, see the code here: https://stackoverflow.com/questions/3858851#3859336

like image 120
HardlyKnowEm Avatar answered Oct 20 '22 21:10

HardlyKnowEm


In Python you can use os.path.expanduser to get the User's home directory.

>>> import os
>>> os.path.expanduser("~")

This is a platform independent way of determining the user's home directory.

You can then concatenate the result to create your final path

os.path.join(os.path.expanduser("~"), 'Documents', 'ArcGIS', 'file1.gdb')
like image 23
Abhijit Avatar answered Oct 20 '22 22:10

Abhijit