Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List home directory without absolute path

Tags:

python

I'm having problem with listing home directory of current user without knowing absolute path to it. I've tried with the following, but it doesn't work:

[root@blackbox source]# python
Python 2.6.6 (r266:84292, Dec  7 2011, 20:38:36)
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir('/root')
['python', '.bashrc', '.viminfo']
>>> os.listdir('~')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '~'
>>>
like image 590
Nemanja Boric Avatar asked Dec 11 '12 23:12

Nemanja Boric


People also ask

What is the absolute path of your home directory?

An absolute path is a path that contains the entire path to the file or directory that you need to access. This path will begin at the home directory of your computer and will end with the file or directory that you wish to access. Absolute paths ensure that Python can find the exact file on your computer.

How do you use absolute path instead of relative path in Python?

Absolute and Relative file paths An absolute file path describes how to access a given file or directory, starting from the root of the file system. A file path is also called a pathname. Relative file paths are notated by a lack of a leading forward slash. For example, example_directory.

How do I give a relative a file path in Python?

A relative path starts with / , ./ or ../ . To get a relative path in Python you first have to find the location of the working directory where the script or module is stored. Then from that location, you get the relative path to the file want.


2 Answers

You need to use the os.path.expanduser() function:

>>> import os.path
>>> os.path.expanduser('~')
'/home/username'
like image 124
Martijn Pieters Avatar answered Oct 24 '22 09:10

Martijn Pieters


You could ask the Operation System like this:

>>> import os
>>> os.environ['HOME']
'/home/noctua'
>>> os.listdir(os.environ['HOME'])
like image 1
Noctua Avatar answered Oct 24 '22 09:10

Noctua