Folder separator on windows are \ but on mac or linux they are /

In [1]:
'c:\\something\\example.jpeg'
Out[1]:
'c:\\something\\example.jpeg'

We escape the backslash in a string with another backslash

In [2]:
r'c:\something\example.jpeg'
Out[2]:
'c:\\something\\example.jpeg'
In [3]:
print(r'c:\something\example.jpeg')
c:\something\example.jpeg
In [4]:
'\\'.join(['folder1', 'folder2', 'folder3', 'example.png'])
Out[4]:
'folder1\\folder2\\folder3\\example.png'

Above filepath will only work on windows

In [5]:
import os

os.path.join()

In [6]:
os.path.join('folder1', 'folder2', 'folder3', 'example.png')
Out[6]:
'folder1\\folder2\\folder3\\example.png'

Above code return the path that is apporpriate for the os we are using.

os.sep()

In [7]:
os.sep
Out[7]:
'\\'

Current working directory as a string value can be obtained the following way. Directory is just a name for folder. cwd is directory where python looks when we don't specify the path for a file. i.e. only file name is specified

os.getcwd()

In [8]:
os.getcwd()
Out[8]:
'C:\\Users\\there\\Python'

os.chdir()

We can change the current working directory with change directory function chdir()

In [9]:
os.chdir("f:\\")
In [10]:
os.getcwd()
Out[10]:
'f:\\'

Absolute file path begins with root folder and gives complete location
Relative file path is always going to be relative with current working directory, it won't contain root folder.

. and .. folders

single . means this directory
two . i.e. .. means parent directory



Let's say there are two folders 'one' and 'two' in my F drive, and 'one' is the cwd.

Relative path of 'one' is
.\

whereas absolulte path of 'one' is:
F:\one

Relative path of the F drive is:
..\

whereas absolulte path of F is:
F:\

Relative path of 'two' is
..\two

whereas absolulte path of 'two' is:
F:\two

If there is a file name some.txt in two, it's relative path is
..\two\some.txt

and it's absolute file path is
F:\two\some.txt


Changing the current working directory back to what it was before.

In [11]:
os.chdir('C:\\Users\\there\\Python')
In [12]:
os.getcwd()
Out[12]:
'C:\\Users\\there\\Python'

os.path.abspath()

In [13]:
os.path.abspath('something.txt')  #will return the string of the absolute path of the path that I pass it.
Out[13]:
'C:\\Users\\there\\Python\\something.txt'
In [14]:
os.path.abspath('..\\..\\something.txt')  #file is in parent folder of the parent folder
Out[14]:
'C:\\Users\\something.txt'

os.path.isabs()

Return true if the file path is absolute, i.e. begins with a root folder.

In [15]:
os.path.isabs('..\\..\\something.txt')
Out[15]:
False
In [16]:
os.path.isabs('F:\\folder\\something.txt')
Out[16]:
True

os.path.relpath()

Will give the relative path between two paths.

In [17]:
os.path.relpath('C:\\folder1\\folder2\\some.txt', 'C:\\folder1')
                #will give the relative path to the first argument from the second argument which is the cwd.
Out[17]:
'folder2\\some.txt'

os.path.dirname()

Path is
F:\folder1\folder2\some.txt

In [18]:
os.path.dirname(r'F:\folder1\folder2\some.txt')  #returns the directory part of the path.
Out[18]:
'F:\\folder1\\folder2'

os.path.basename()

In [19]:
os.path.basename('F:\\folder1\\folder2\\some.txt')  #name after the last \ i.e. the file name.
Out[19]:
'some.txt'

os.path.exists()

Returns true if the file path actually exists and returns false if it doesn't.

In [20]:
os.path.exists('C:\\something.txt')
Out[20]:
False
In [21]:
os.path.exists('C:\\Program Files')
Out[21]:
True
In [22]:
os.path.exists('F:\\Entertainment\\movies\\Up\\Up.mkv')
Out[22]:
True

os.path.isfile()

In [23]:
os.path.isfile('F:\\Entertainment\\movies\\Up\\Up.mkv')
Out[23]:
True
In [24]:
os.path.isfile('C:\\something_I_Made_Up')
Out[24]:
False

os.path.isdir()

In [25]:
os.path.isdir('C:\\Program Files')
Out[25]:
True
In [26]:
os.path.isdir('C:\\something_I_Made_Up')
Out[26]:
False

Above code returned false because it couldn't verify the path is a folder or a file without a extension.
os.path.isfile() and os.path.isdir() works only when the path exists otherwise they will return false.

os.path.getsize()

Gives the size in bytes.

In [27]:
os.path.getsize('f:\\Entertainment\\Movies\\Interstellar\\Interstellar.mp4')
Out[27]:
2431697820
In [28]:
size = os.path.getsize('f:\\Entertainment\\Movies\\Interstellar\\Interstellar.mp4')
In [29]:
newsize = size/(1024*1024)  #give the size in megabyte
In [30]:
newsize/1024 #will give the size in gigabyte
Out[30]:
2.2646950744092464

os.listdir()

Will return a list of all the files/folders inside the path passed to it.

In [31]:
os.listdir('F:\\Entertainment\\Music')
Out[31]:
['Mixtapes',
 'Music Videos',
 'My Songs',
 'Text file I created to confirm os.listdir() shows filenames too and  will delete this immediately after that.txt']

listdir() is not in the path module of the os


Program to retrieve the total size of all 'files' in a folder.

In [32]:
totalSize = 0
In [33]:
for filename in os.listdir('F:\\Entertainment\\Music'):
    if not os.path.isfile(os.path.join('F:\\Entertainment\\Music', filename)):
        continue
    totalSize = totalSize + os.path.getsize(os.path.join('F:\\Entertainment\\Music', filename))
In [34]:
print(totalSize)
19

os.makedirs()

To create new folders - can pass either absolute or relative path

In [35]:
os.makedirs('F:\\NewFolder1\\something\\newfolder2')

All the folders in the path above didn't existed, so python created all of them.

In [36]:
os.makedirs('F:\\NewFolder1\\something\\newfolder2')
#FileExistsError
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-36-c580c20f531f> in <module>()
----> 1 os.makedirs('F:\\NewFolder1\\something\\newfolder2')
      2 #FileExistsError

~\Anaconda3\lib\os.py in makedirs(name, mode, exist_ok)
    218             return
    219     try:
--> 220         mkdir(name, mode)
    221     except OSError:
    222         # Cannot rely on checking for EEXIST, since the operating system

FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'F:\\NewFolder1\\something\\newfolder2'
In [37]:
try:
    os.makedirs('F:\\NewFolder1\\something\\newfolder2')
except FileExistsError:
    print('Directory already exists')
Directory already exists