Python windows linux directory

How to find the real user home directory using python?

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) 

You may want to checkout unix command(shortcut): ~user It takes you to home directory of current user. On windows have no idea.

This should be marked a duplicate of How to get the home directory in Python? since that question’s accepted answer works on Python 3 and this question’s does not.

9 Answers 9

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.

True, but changing the environment variable as in the question will «fool» this method as well. Now, why one would want to do that, I can’t say. 🙂

@calmh: Yes, I changed it to use ‘~user’ which should work on Linux and Windows (here I am not 100% sure because I don’t have Windows to test it 😉 ).

Читайте также:  Настройка proxy server linux

This is working in Linux, But not in windows. In windows it just joins the «C:\Documents and settings» to the username passed.

@asdfg : It sounds to me like it worked correctly. But I too thought it had failed the first time I tried, because at first I was passing the literal string ‘~user’ (which really needs to be something literal such as ‘~Bob’) instead of just ‘~’ (which appends the current user).

Источник

What is the filepath difference between window and linux in python3?

This creates the file in the folder named users, but when I run the program on a linux system, it instead creates, in the root folder, a file named users\userName.txt How is the path definition different for python 3 in linux?

Storing files directly in a home or profile directory is a bad practice, especially on Windows, in which documents belong in FOLDERID_Documents . Do not use the default location for this directory relative to the USERPROFILE environment variable. A user or administrator can relocate this folder anywhere. Use ShGetKnownFolderPath .

2 Answers 2

Windows has drives (C:, D:, X: etc) and backslashes or double backslashes, e.g.

C:\Users\JohnSmith is the same as C:\\Users\\JohnSmith

On Linux, there are no drives (per se) and forward slashes, e.g. /home/name

The best way to get a feel for paths is by using os. Try typing this into your python terminal print(os.path.abspath(‘.’))

It’s not different in python 3 in linux it’s different in linux . Generally speaking *nix file paths use / as a directory separator, where as windows uses \ (for what ever reason).

In python 3 you can use the pathlib.Path to abstract your code from the OS. So you can do something like

The tilde ~ refers to a user’s home directory. Python will figure out which file system the code is running on and do the right thing to map directory separators. You could also do

Читайте также:  Combining files in linux

to address a specific user directory, the / refers to the root of the file system and should work on Linux and Windows (although I haven’t tested that).

Источник

What is a cross-platform way to get the home directory?

I need to get the location of the home directory of the current logged-on user. Currently, I’ve been using the following on Linux:

This is marked a duplicate of How to find the real user home directory using python, but I voted to reopen because this answer works on Python 3 and the older answer does not.

5 Answers 5

You want to use os.path.expanduser.
This will ensure it works on all platforms:

from os.path import expanduser home = expanduser("~") 

If you’re on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path home = str(Path.home()) 

But it’s usually better not to convert Path.home() to string. It’s more natural to use this way:

with open(Path().home() / ".ssh" / "known_hosts") as f: lines = f.readlines() 

it should be noted that if the user is logged on to a domain on windows and has their profile home folder set in active directory then this will report that mapped network folder instead of the local home directory

I wonder why nobody else mentioned it in this question, but if you need to know where another user’s home directory is you can use os.path.expanduser(‘~username’) . Probably applies only for Linux though.

The result is the same. If you generally are working with pathlib, you may prefer the pathlib solution (and omit the call of str ). If you just want the path as string, they both do the same.

@dcolish please remove str() from the answer. It’s so much more natural to build a path with the slash / such as `Path.home() / «location_of_a_file.txt».

Читайте также:  Play on linux centos

I found that pathlib module also supports this.

from pathlib import Path >>> Path.home() WindowsPath('C:/Users/XXX') 

I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.

import os print(os.path.expanduser("~")) 
PS C:\Python> & C:/Python38/python.exe c:/Python/test.py C:\Users\mXXXXX 
rxxx@xx:/mnt/c/Python$ python3 test.py /home/rxxx 

I also tested it on Python 2.7.17 and that works too.

This can be done using pathlib , which is part of the standard library, and treats paths as objects with methods, instead of strings.

from pathlib import Path home: str = str(Path('~').expanduser()) 

This doesn’t really qualify for the question (it being tagged as cross-platform ), but perhaps this could be useful for someone.

How to get the home directory for effective user (Linux specific).

Let’s imagine that you are writing an installer script or some other solution that requires you to perform certain actions under certain local users. You would most likely accomplish this in your installer script by changing the effective user, but os.path.expanduser(«~») will still return /root .

The argument needs to have the desired user name:

Note that the above works fine without changing EUID, but if the scenario previously described would apply, the example below shows how this could be used:

import os import pwd import grp class Identity(): def __init__(self, user: str, group: str = None): self.uid = pwd.getpwnam(user).pw_uid if not group: self.gid = pwd.getpwnam(user).pw_gid else: self.gid = grp.getgrnam(group).gr_gid def __enter__(self): self.original_uid = os.getuid() self.original_gid = os.getgid() os.setegid(self.uid) os.seteuid(self.gid) def __exit__(self, type, value, traceback): os.seteuid(self.original_uid) os.setegid(self.original_gid) if __name__ == '__main__': with Identity("hedy", "lamarr"): homedir = os.path.expanduser(f"~/") with open(os.path.join(homedir, "install.log"), "w") as file: file.write("Your home directory contents have been altered") 

Источник

Оцените статью
Adblock
detector