Thursday, October 1, 2020

7 Frequent Python 'os' Package Uses



(base) C:\Users\ashish\Desktop\TEST>tree /f

C:.
│   TEST2.txt
│
└───TEST1
    │   TEST1.2.txt
    │
    └───TEST1.1
            TEST1.1.1.txt 

= = = = =

1. List all the subdirectories and files:

(base) C:\Users\ashish\Desktop\TEST>python
Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir('.')
['TEST1', 'TEST2.txt']
>>>

= = = = =

2. Recursively get all the subdirectories and files under the current folder (signified by "."):

>>> for dirpath, subdirs, files in os.walk("."):
...  print("dirpath:", dirpath)
...  for s in subdirs:
...   print("subdir:", s)
...  for f in files:
...   print("file:", f)
...
dirpath: .
subdir: TEST1
subdir: TEST4
file: TEST2.txt
file: TEST3.txt

dirpath: .\TEST1
subdir: TEST1.1
file: TEST1.2.txt

dirpath: .\TEST1\TEST1.1
file: TEST1.1.1.txt

dirpath: .\TEST4
>>> 

= = = = =

3. Call a OS Shell (or Windows CMD) command from Python Shell:

>>> os.system("tree /f")

C:.
│   TEST2.txt
│   TEST3.txt
│
├───TEST1
│   │   TEST1.2.txt
│   │
│   └───TEST1.1
│           TEST1.1.1.txt
│
└───TEST4
0 

Note: 0 at the end signifies 'successful' exit.

= = = = =

4. Create a "Path" from Strings:

"os.path.join" joins strings with the character representing 'path separater' for the OS.

>>> os.path.join("DIR1", "DIR2")
'DIR1\\DIR2' 

>>> os.path.join("DIR1", "DIR2", "DIR3")
'DIR1\\DIR2\\DIR3' 

>>> os.path.sep
'\\'

= = = = =

5. Get 'current working directory':

>>> os.getcwd()
'C:\\Users\\ashish\\Desktop\\TEST' 

= = = = =

6. Change Directory:

>>> os.chdir("TEST1")

>>> os.listdir()
['TEST1.1', 'TEST1.2.txt'] 

>>> os.getcwd()
'C:\\Users\\ashish\\Desktop\\TEST\\TEST1' 

= = = = =

7. Getting environment variables:

>>> import os
>>> os.environ['PATH']
'E:\\programfiles\\Anaconda3;E:\\programfiles\\Anaconda3\\Lib...' 

= = = = =

No comments:

Post a Comment