Now, we are going to learn about os.path(). It is used for path manipulations. In this section, we will look at some of the functions that the os module offers for pathnames.
Start the python3 console:
student@ubuntu:~$ python3
Python 3.6.6 (default, Sep 12 2018, 18:26:19)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.>>
- os.path.absname(path): Returns the absolute version of your pathname.
>>> import os
>>> os.path.abspath('sample.txt')
'/home/student/work/sample.txt'
- os.path.dirname(path): Returns the directory name of your path.
>>> os.path.dirname('/home/student/work/sample.txt')
'/home/student/work'
- os.path.basename(path): Returns the base name of your path.
>>> os.path.basename('/home/student/work/sample.txt')
'sample.txt'
- os.path.exists(path): Returns True if path refers to the existing path.
>>> os.path.exists('/home/student/work/sample.txt')
True
- os.path.getsize(path): Returns the size of the entered path in bytes.
>>> os.path.getsize('/home/student/work/sample.txt')
39
- os.path.isfile(path): Checks whether the entered path is an existing file or not. Returns True if it is a file.
>>> os.path.isfile('/home/student/work/sample.txt')
True
- os.path.isdir(path): Checks whether the entered path is an existing directory or not. Returns True if it is a directory.
>>> os.path.isdir('/home/student/work/sample.txt')
False