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: '~'
>>>
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.
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.
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.
You need to use the os.path.expanduser()
function:
>>> import os.path
>>> os.path.expanduser('~')
'/home/username'
You could ask the Operation System like this:
>>> import os
>>> os.environ['HOME']
'/home/noctua'
>>> os.listdir(os.environ['HOME'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With