The program is based on the owner we have to return the absolute path of files from the path specified, the path specified can be from any directory. This program has to be done in python using windows.
I think this might be what you are looking for
import os
print(os.getcwd())
This prints out the current working directory, which includes the name of the user which I'm guessing is what you are after.
If you just want the username
import os
os.getlogin()
Related
I want to open a file in the desktop, or anywhere else in the C:/Users/USERNAME/ directory. but I don't know what the code to get the username is.
for example, in batch-file programming I could use:]
c:/Users/%USERNAME%/...
I want to use it in the open function. I have tried both:
open('C:/Users/%%USERNAME/Desktop/data3.txt')
open('C:/Users/%USERNAME%/Desktop/data3.txt')
I know there should be an import that can give the username to my code. But I don't know what it is. And I also would like to know if I can use the username like %USERNAME% or %%USERNAME or a single thing that doesn't need any import.
Three ways to do this using the os module:
Use os.getlogin():
import os
>>> os.path.join("C:", os.sep, "Users", os.getlogin(), "Desktop")
'C:\\Users\\your_username\\Desktop'
Use os.environ():
>>> os.path.join(os.environ['userprofile'], "Desktop")
'C:\\Users\\your_username\\Desktop'
Use os.path.exapndvars():
>>> os.path.join(os.path.expandvars("%userprofile%"), "Desktop")
'C:\\Users\\your_username\\Desktop'
you can use expanduser and ~ for that :
import os
open(os.path.expanduser('~\\Desktop\\data3.txt'))
or if you want to use os.path.join :
open(os.path.join(os.path.expanduser('~'), 'Desktop', 'data3.txt'))
(I'm not used to writing python programs for other users to use, so hopefully this question is appropriate.)
My users will download a file generic_file.csv and let's assume that this file will be saved in the "current directory".
So, I write a python script named reader.py
#!/usr/bin/env python
from __future__ import (print_function, absolute_import)
import os
import csv
import random
import string
cd_path = os.getcwd() # return path of current directory
filename = 'generic_file.csv' # filename 'test_enigma.csv'
filepath = os.path.join(os.getcwd(), filename) # returns path to open fname
print(filepath)
Now, if the user runs this in the terminal with python reader.py, it should output the name of the file, ONLY IF the file was saved in the current directory.
That's inconvenient. Most users will just download the file, and they would like reader.py to change to the subdirectory Downloads and read generic_file.csv from that directory.
(1) How does one use os.chdir() to work for every user?
(2) What is the standard way to do this if I was writing third-party software? I imagine I would have the user download the specific CSV file and Python script together.
If you are looking to get the path name of User A's download file, you can do os.path.expanduser('~/Downloads'). This will return /Users/A/Downloads
I'm running a script which prompts the user to select a directory, saves a plot to that directory and then uses subprocess to open that location:
root = Tkinter.Tk()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
fig.savefig(dirname+'/XXXXXX.png',dpi=300)
plt.close("all")
root.withdraw()
subprocess.Popen('explorer dirname')
When I run the file I select a sub-directory in D:\Documents and the figure save is correct. However the subprocess simply opens D:\Documents as opposed to D:\Documents\XXX.
Ben
To open a directory with the default file explorer:
import webbrowser
webbrowser.open(dirname) #NOTE: no quotes around the name
It might use os.startfile(dirname) on Windows.
If you want to call explorer.exe explicitly:
import subprocess
subprocess.check_call(['explorer', dirname]) #NOTE: no quotes
dirname is a variable. 'dirname' is a string literal that has no relation to the dirname name.
You are only passing the string 'dirname' not the variable that you have named dirname in your code. Since you (presumably) don't have a directory called dirname on your system, explorer opens the default (Documents).
You may also have a problem with / vs \ in directory names. As shown in comments, use os.path module to convert to the required one.
You want something like
import os
win_dir = os.path.normpath(dirname)
subprocess.Popen('explorer "%s"' %win_dir)
or
import os
win_dir = os.path.normpath(dirname)
subprocess.Popen(['explorer', win_dir])
Add ,Shell=True after 'explorer dirname'
If Shell is not set to True, then the commands you want to implement must be in list form (so it would be ['explorer', ' dirname']. You can also use shlex which helps a lot if you don't want to make Shell = True and don't want to deal with lists.
Edit: Ah I miss read the question. often you need a direct path to the directory, so that may help.
How can I set the current path of my python file "myproject.py" to the file itself?
I do not want something like this:
path = "the path of myproject.py"
In mathematica I can set:
SetDirectory[NotebookDirectory[]]
The advantage with the code in Mathematica is that if I change the path of my Mathematica file, for example if I give it to someone else or I put it in another folder, I do not need to do anything extra. Each time Mathematica automatically set the directory to the current folder.
I want something similar to this in Python.
The right solution is not to change the current working directory, but to get the full path to the directory containing your script or module then use os.path.join to build your files path:
import os
ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
# then:
myfile_path = os.path.join(ROOT_PATH, "myfile.txt")
This is safer than messing with current working directory (hint : what would happen if another module changes the current working directory after you did but before you access your files ?)
I want to set the directory in which the python file is, as working directory
There are two step:
Find out path to the python file
Set its parent directory as the working directory
The 2nd is simple:
import os
os.chdir(module_dir) # set working directory
The 1st might be complex if you want to support a general case (python file that is run as a script directly, python file that is imported in another module, python file that is symlinked, etc). Here's one possible solution:
import inspect
import os
module_path = inspect.getfile(inspect.currentframe())
module_dir = os.path.realpath(os.path.dirname(module_path))
Use the os.getcwd() function from the built in os module also there's os.getcwdu() which returns a unicode object of the current working directory
Example usage:
import os
path = os.getcwd()
print path
#C:\Users\KDawG\Desktop\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?
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
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')
You want to use the evironment variable HOME, something like this:
import os
homeDir = os.environ["HOMEPATH"]
file = open(homeDir+"Documents\ArcGIS\file1.gdb")
file.write("Hello, World")
file.close()
Notice that I've used HOMEPATH considering you're using Windows, it may be wrong depending on your OS. Take a look at this: http://en.wikipedia.org/wiki/Environment_variable