13.1.1. OS Module Basics#
import os
13.1.1.1. Get current working directory#
os.getcwd() # Most important command
'/Users/sahilchoudhary/Desktop/Projects/Digital Ebook/Draft-Codes-main/Chapter files'
13.1.1.2. List the files and folders of current directory#
os.listdir()[0:5]
['Licenses.ipynb',
'Zip.ipynb',
'Any() vs All()-Copy1.ipynb',
'Untitled7.ipynb',
'DEBUGGING TITLE.ipynb']
13.1.1.3. Changing the working directory#
os.chdir('C:\\users\\Sahil Choudhary\\Desktop') # Most important command
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Input In [4], in <cell line: 1>()
----> 1 os.chdir('C:\\users\\Sahil Choudhary\\Desktop')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\users\\Sahil Choudhary\\Desktop'
13.1.1.4. List the files and folders of particular directory#
os.listdir("C:\\Users\\Sahil Choudhary\\Documents\\Test folder\\Parent folder")
['Parent file outside.txt', 'Sub folder 1', 'Sub folder 2']
os.listdir() #_static
os.chdir("_static")
os.getcwd()
'C:\\Users\\Sahil Choudhary\\Book\\Python\\_build\\html\\_static'
13.1.1.5. Making a new directory#
os.mkdir('Test')
13.1.1.6. OS.walk#
13.1.1.6.1. Get file names and folder names and the files present in subfolders all in one go#
path='C:\\Users\\Sahil Choudhary\\Documents\\Test folder\\Parent folder'
for root_path,sub_directories,files in os.walk(path):
# os.walk(path) gives 3 things
# parent directory
# subdirectory
# files
print('Parent folder = ',root_path.split('\\')[-1])
print('Sub directories = ',sub_directories)
print('Files = ',files)
print('---------')
Parent folder = Parent folder
Sub directories = ['Sub folder 1', 'Sub folder 2']
Files = ['Parent file outside.txt']
---------
Parent folder = Sub folder 1
Sub directories = []
Files = ['sub folder 1 file.txt']
---------
Parent folder = Sub folder 2
Sub directories = ['sub sub folder 2']
Files = ['sub folder 2 file.txt']
---------
Parent folder = sub sub folder 2
Sub directories = []
Files = ['sub sub folder 2 file.txt']
---------