I'm attempting to read and write files from a User Directory, (C:\Users\USERNAME\Test Source) But I've been unsuccessful in finding any resources on how I can auto detect the name of the user, USERNAME in the above example, or anyway that I can have it read and write to the directory without knowledge off what a users name is.
Could anyone point me towards the right direction or methods for this, if it's even a logical request? I'm not sure how much difference, if any, it makes but this program is being written in Python 2.7.
The simplest way is this:
import os
print os.path.expanduser('~')
Append your folder to the path like so:
userdir = os.path.expanduser('~')
print os.path.join(userdir, 'Test Source')
Besides requiring the least lines of code, this method has the advantage of working under every OS (Linux, Windows XP / 7 / 8 / etc).
You can use in windows command line
echo %username%
or
whoami
for getting the username of the user who is currently logged in .
Store it in a variable and then append it to the path name.
You can also use
‘C:\users\%username%\file‘
directly .To check through whoami do
l=`whoami`
echo $l
Use the %userprofile% variable in your path if you're on Windows:
%userprofile%\Test Source\file.txt
Try:
>>> import getpass
>>> import os.path
>>> usename = getpass.getuser()
>>> mypath = os.path.join("C:\Users", username, "Test Source")
Related
I have a little problem with ~ in my paths.
This code example creates some directories called ~/some_dir and do not understand that I wanted to create some_dir in my home directory.
my_dir = "~/some_dir"
if not os.path.exists(my_dir):
os.makedirs(my_dir)
Note this is on a Linux-based system.
You need to expand the tilde manually:
my_dir = os.path.expanduser('~/some_dir')
The conversion of ~/some_dir to $HOME/some_dir is called tilde expansion and is a common user interface feature. The file system does not know anything about it.
In Python, this feature is implemented by os.path.expanduser:
my_dir = os.path.expanduser("~/some_dir")
That's probably because Python is not Bash and doesn't follow same conventions. You may use this:
homedir = os.path.expanduser('~')
I'm trying to make a script that's going to do some stuff via command line. Its usage should look somewhat like this:
C:\users\me> appname startprocess
but if I'm trying to release this, I need it to be really handy for everyone to use and that needs the PATH variable to be set to my script's location.
I want my script to handle this task by itself. Can my script edit my PATH variable permanently? If so, how?
Most questions on this topic are mostly about how to set the path variable for python scripts instead of writing script that could do that by itself.
For adding the current working directory to the PATH, you can use this piece of code:
import os
import sys
pwd = os.getcwd()
sys.path.append(pwd)
And for running a shell script, use this:
import subprocess
subprocess.run('Your Command', shell = True)
If you want to check the output of the command:
stdout = subprocess.check_output('Your Command', shell = True)
print(stdout.decode())
Wondering if you know if there is a slick way to get full username from shell?
example: if my unix username is froyo then I want to get my full name
as registered in the system in this case [froyo === Abhishek Pratap]
finger command does it but for all the logged in users at the same time ..so that needs some parsing to get the right value. Anything slicker ?
Anything from inside python would be great too.
Thanks!
-Abhi
One way to achieve this is using pwd.getpwuid and os.getuid:
>>> import os
>>> import pwd
>>> pwd.getpwuid(os.getuid())[4]
This is the traditional Unix way of doing it (based on standard C library calls).
I see that if we change the HOME (linux) or USERPROFILE (windows) environmental variable and run a python script, it returns the new value as the user home when I try
os.environ['HOME']
os.exp
Is there any way to find the real user home directory without relying on the environmental variable?
edit:
Here is a way to find userhome in windows by reading in the registry,
http://mail.python.org/pipermail/python-win32/2008-January/006677.html
edit:
One way to find windows home using pywin32,
from win32com.shell import shell,shellcon
home = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, None, 0)
I think os.path.expanduser(path) could be helpful.
On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.
On Unix, an initial ~ is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in module pwd. An initial ~user is looked up directly in the password directory.
On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.
If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.
So you could just do:
os.path.expanduser('~user')
from pathlib import Path
str(Path.home())
works in Python 3.5 and above. Path.home() returns a Path object providing an API I find very useful.
I think os.path.expanduser(path) is the best answer to your question, but there's an alternative that may be worth mentioning in the Unix world: the pwd package. e.g.
import os, pwd
pwd.getpwuid(os.getuid()).pw_dir
For windows;
import os
homepath = os.path.expanduser(os.getenv('USERPROFILE'))
will give you a handle to current user's home directory and
filepath = os.path.expanduser(os.getenv('USERPROFILE'))+'\\Documents\\myfile.txt'
will give you a handle to below file;
C:\Users\urUserName\Documents\myfile.txt
home_folder = os.getenv('HOME')
This should work on Windows and Mac OS too, works well on Linux.
Really, a change in environment variable indicates that the home must be changed. So every program/script should have the new home in context; also the consequences are up to the person who changed it.
I would still stick with
home = os.getenv('USERPROFILE') or os.getenv('HOME')
what exactly is required?
I realize that this is an old question that has been answered but I thought I would add my two cents. The accepted answer was not working for me. I needed to find the user directory and I wanted it to work with and without sudo. In Linux, my user directory is "/home/someuser" but my root directory is "/root/". However, on my Mac, the user directory is "/Users/someuser". Here is what I ended up doing:
_USERNAME = os.getenv("SUDO_USER") or os.getenv("USER")
_HOME = os.path.expanduser('~'+_USERNAME)
This worked both with and without sudo on Mac and Linux.
get (translated) user folder names on Linux:
from gi.repository import GLib
docs = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOCUMENTS)
desktop = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DESKTOP)
pics = GLib.get_user_special_dir(GLib.USER_DIRECTORY_PICTURES)
videos = GLib.get_user_special_dir(GLib.USER_DIRECTORY_VIDEOS)
music = GLib.get_user_special_dir(GLib.USER_DIRECTORY_MUSIC)
downloads = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOWNLOAD)
public = GLib.get_user_special_dir(GLib.USER_DIRECTORY_PUBLIC_SHARE)
templates = GLib.get_user_special_dir(GLib.USER_DIRECTORY_TEMPLATES)
print(docs)
print(desktop)
print(pics)
print(videos)
print(music)
print(downloads)
print(public)
print(templates)
On Linux and other UNIXoids you can always take a peek in /etc/passwd. The home directory is the sixth colon-separated field in there. No idea on how to do better than the environment variable on Windows though. There'll be a system call for it, but if it's available from Python, ...
Simply moving the file to ~/.Trash/ will not work, as if the file os on an external drive, it will move the file to the main system drive..
Also, there are other conditions, like files on external drives get moved to /Volumes/.Trash/501/ (or whatever the current user's ID is)
Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python
Based upon code from http://www.cocoadev.com/index.pl?MoveToTrash I have came up with the following:
def get_trash_path(input_file):
path, file = os.path.split(input_file)
if path.startswith("/Volumes/"):
# /Volumes/driveName/.Trashes/<uid>
s = path.split(os.path.sep)
# s[2] is drive name ([0] is empty, [1] is Volumes)
trash_path = os.path.join("/Volumes", s[2], ".Trashes", str(os.getuid()))
if not os.path.isdir(trash_path):
raise IOError("Volume appears to be a network drive (%s could not be found)" % (trash_path))
else:
trash_path = os.path.join(os.getenv("HOME"), ".Trash")
return trash_path
Fairly basic, and there's a few things that have to be done seperatly, particularly checking if the filename already exist in trash (to avoid overwriting) and the actual moving to trash, but it seems to cover most things (internal, external and network drives)
Update: I wanted to trash a file in a Python script, so I re-implemented Dave Dribin's solution in Python:
from AppKit import NSURL
from ScriptingBridge import SBApplication
def trashPath(path):
"""Trashes a path using the Finder, via OS X's Scripting Bridge.
"""
targetfile = NSURL.fileURLWithPath_(path)
finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder")
items = finder.items().objectAtLocation_(targetfile)
items.delete()
Usage is simple:
trashPath("/tmp/examplefile")
Alternatively, if you're on OS X 10.5, you could use Scripting Bridge to delete files via the Finder. I've done this in Ruby code here via RubyCocoa. The the gist of it is:
url = NSURL.fileURLWithPath(path)
finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder")
item = finder.items.objectAtLocation(url)
item.delete
You could easily do something similar with PyObjC.
A better way is NSWorkspaceRecycleOperation, which is one of the operations you can use with -[NSWorkspace performFileOperation:source:destination:files:tag:]. The constant's name is another artifact of Cocoa's NeXT heritage; its function is to move the item to the Trash.
Since it's part of Cocoa, it should be available to both Python and Ruby.
In Python, without using the scripting bridge, you can do this:
from AppKit import NSWorkspace, NSWorkspaceRecycleOperation
source = "path holding files"
files = ["file1", "file2"]
ws = NSWorkspace.sharedWorkspace()
ws.performFileOperation_source_destination_files_tag_(NSWorkspaceRecycleOperation, source, "", files, None)
The File Manager API has a pair of functions called FSMoveObjectToTrashAsync and FSPathMoveObjectToTrashSync.
Not sure if that is exposed to Python or not.
Another one in ruby:
Appscript.app('Finder').items[MacTypes::Alias.path(path)].delete
You will need rb-appscript gem, you can read about it here