Python home directory linux

What is the correct cross-platform way to get the home directory in Python?

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:

However, this does not work on Windows. What is the correct cross-platform way to do this ?

4 Answers 4

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

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

username’) . Probably applies only for Linux though.

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.

Output Linux (Ubuntu):

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

I found that pathlib module also supports this.

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:

Источник

How to find the real user home directory using python?

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 tried, 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,

user It takes you to home directory of current user. On windows have no idea.

9 Answers 9

On Unix and Windows, return the argument with an initial component of

user replaced by that user‘s home directory.

On Unix, an initial

Читайте также:  Правильная активация windows 10

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.

Источник

Как найти реальный домашний каталог пользователя с помощью python?

Я вижу, что если мы изменим переменную среды HOME(linux) или USERPROFILE(windows) и запустим скрипт python, он вернет новое значение в качестве дома пользователя, когда я попытался, ОС.энвирон[‘домой’] ОС.exp

есть ли способ найти реальный домашний каталог пользователя, не полагаясь на переменную среды?

edit:
Один из способов найти Windows home с помощью pywin32,

9 ответов

Я думаю os.path.expanduser(path) может быть полезным.

в Unix и Windows верните аргумент с начальным компонентом

user заменен домашним каталогом этого пользователя.

заменяется переменной окружения HOME, если она установлена; в противном случае домашний каталог текущего пользователя просматривается в каталоге паролей через встроенный модуль pwd . исходная

user ищется непосредственно в каталоге паролей.

в Windows, HOME и USERPROFILE будут использоваться, если установлено, в противном случае сочетание HOMEPATH и HOMEDRIVE будет использоваться. исходная

user обрабатывается путем удаления последнего компонента каталога из созданного пути пользователя, полученного выше.

если расширение не удается, или если путь не начинается с Тильды, путь возвращается без изменений.

так что вы могли бы вобще:

Я думаю os.path.expanduser(path) — лучший ответ на ваш вопрос, но есть альтернатива, которую стоит упомянуть в мире Unix: pwd пакета. например,

Это должно работать на Windows и Mac OS тоже, хорошо работает на Linux.

работает в Python 3.5 и выше. Path.home() возвращает Path объект предоставления API Я нахожу очень полезным.

даст вам дескриптор домашнего каталога текущего пользователя и

даст вам дескриптор ниже файла;

действительно, изменение переменной среды указывает на то, что дом должен быть изменен. Таким образом, каждая программа/скрипт должна иметь новый дом в контексте; также последствия зависят от человека, который его изменил. Я бы все равно остался с home = os.getenv(‘USERPROFILE’) or os.getenv(‘HOME’)

что именно требуется?

Я понимаю, что это старый вопрос, на который был дан ответ, но я думал, что добавлю свои два цента. Принятый ответ не работает для меня. Мне нужно было найти каталог пользователя, и я хотел, чтобы он работал с и без sudo . В Linux мой пользовательский каталог — «/ home / someuser», но мой корневой каталог — » / root/». Однако на моем Mac каталог пользователя «/ Users / someuser». Вот что я в итоге сделал:

это работало как с, так и без sudo на Mac и Линукс.

получить (переведенные) имена папок пользователя в Linux:

в Linux и других UNIXoids вы всегда можете заглянуть в /etc/passwd . Домашний каталог-это шестое поле, разделенное двоеточием. Однако нет идеи о том, как сделать лучше, чем переменная среды в Windows. Для этого будет системный вызов, но если он доступен из Python.

Читайте также:  Стабильный linux для дома

Источник

Python directory

last modified September 14, 2020

Python directory tutorial shows how to work with directories in Python. We show how to create, rename, move, or list a directory in Python.

Directory definition

Directory is an organizing unit in a computer’s file system for storing and locating files. Directories are hierarchically organized into a tree of directories. Directories have parent-child relationships. A directory is sometimes also called a folder.

There are multiple functions for manipulating directories in Python. They are located in the os and pathlib modules. In the tutorial, we work with the pathlib module, which has the more modern API.

Python create directory

The Path.mkdir creates a single directory or multiple directories, including intermediate directories.

If a directory exists, a FileExistsError is raised.

The example creates a directory with Path’s mkdir function.

When we run the program twice, an exception is thrown. To get around this issue, we can check if a directory already exists.

Before we create the directory, we check if it already exists with the Path.exists function. We also catch a possible exception.

Another solution is to use the exist_ok flag. If this flag is set to True , the FileExistsError is ignored.

In this example, we ignore the FileExistsError exceptions.

Python create temporary directory

The tempfile.TemporaryDirectory function securely creates a temporary directory. On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.

The example creates a temporary directory. When the program finishes, the directory is destroyed.

The program created a temporary directory in the special /tmp directory, which is used for such purposes on Linux.

Python rename directory

The Path.rename function renames a directory.

In the example, we rename the test directory to test2 .

Python remove directory

A directory is removed with the Path.rmdir function. The directory must be empty.

The example deletes the test2 directory.

Python move directory

The shutil.move function moves a directory.

The shutil.move recursively moves a file or directory (src) to another location (dst) and returns the destination.

There are two copy functions: copy and copy2 ; the default is copy2 . They differ how they handle file metadata. The copy2 tries to preserve all the file metadata, while the copy does not.

The example moves the contents of the doc directory to docs2 .

We create the docs directory and some files.

We run the program and show the contents of the new directory.

Python current working directory

The Path.cwd function returns a new path object representing the current directory.

The example changes directories and prints the current directory.

Python home directory

The Path.home function returns a new path object representing the user’s home directory.

The program prints the home directory of the user that launched it.

Python directory parents

The Path.parent retunrs the parent of the path and the Path.parents a sequence of ancestors of the path.

Читайте также:  Windows any time upgrade

The example prints the various parents of the current working directory.

Python list directory contents

The Path.iterdir yields path objects of the directory contents. The children are yielded in arbitrary order, and the special entries ‘.’ and ‘..’ are not included.

The example lists the files and directories of the current working directory. The list is non-recursive.

Python check if path is directory

The Path.is_dir returns True if the path points to a directory.

In the example, we list all immediate subdirectories of the current working directory.

In our case, we have three subdirectories.

Python list directory recursively

The path.rglob yields all the files that match the given simple pattern recursively.

In the example, we recursively walk the contents of the parent directory and print all Python files.

In this tutorial, we have worked with directories in Python.

Источник

Python Directory

Summary: in this tutorial, you’ll learn how to manipulate directories using Python built-in functions

Get the current working directory

The directory that the Python program is in is known as the current working directory for that program. In order to get the current working directory you’ll need to use the os module with the function getcwd() as follows:

To change the current working directory you can use function chdir(). You just pass the current working directory you want to change to as follows:

Join and split a path

To make a program work across platforms including Windows, Linux, and Unix, you need to use a platform-independent file and directory path. Python provides a submodule os.path that contains several useful functions and constants to join and split paths.

The join() function joins path components together and returns a path with exact platform separator for instance in windows backslash () and Unix (/)

The split() function splits path into path components without path separator. Here’s an example of using join() and split() functions:

Test if a path is a directory

In order to check a path exists in a system and a path is a directory you can use the functions exists() and isdir() in the submodule os.path as below:

Create a directory

To create a new directory you use mkdir() or makedirs() functions of os module. And you should always check if a directory exists first before creating a new directory.

The following example creates a new directory called python under the c:\temp directory.

Rename a directory

To rename the directory you use os.rename() function. You need to pass the directory you want to change and the new path.

Delete a directory

To delete a directory, you use function rmdir() function as follows:

Traverse a directory recursively

Python provides os.walk() function that allows you to traverse a directory recursively. The os.walk() function returns the root directory, the sub-directories, and files.

The following example shows how to print all files and directories in the c:\temp directory:

Источник

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