Sunday, November 16, 2014

Python Module: os

Module os is the most common module to use operating system dependent functions.
Usually use to build up folder structure or get directory, as well as get environment variable values.

Case 1: 
common os functions

Example:
import os

# a dictionary to store string environment
os.environ

# to get environment value
os.getenv('HOME')
os.getenv('USERNAME')

# to list the file and subdirectory names underneath a path
os.listdir('c:/test/')

# to create a new directory/folder
os.mkdir('c:/test/subdir')

# to remove a file
os.remove('c:/test/test.txt')

# to remove empty folder
os.rmdir('c:/test/')

# to rename a file or folder
os.rename('c:/test/test.txt', 'c:/test/test.py')

# create symbolic link (Linux/Unix Only)
os.symlink('c:/test/test.txt', 'c:/test/symTest.txt')

# depth first iterate files and folders underneath the directory
for root, folders, files in os.walk('c:/test/'):
    print root, folders, files

Case 2: 
os.path is a very useful class to deal with directory path.

Example:
import os

# to get file base name only
os.path.basename('c:/test/test.txt')

# to split file name and its extension
os.path.splitext('test.txt')

# to get folder directory path only
os.path.dirname('c:/test/test.txt')

# to split file base name and directory
os.path.split('c:/test/test.txt')

# to check whether file or directory exists
os.path.exists('c:/test/test.txt')

# to check whether is a file
os.path.exists('c:/test/test.txt')

# to check whether is a directory
os.path.exists('c:/test/')

# to make a path by path components
os.path.join('c:/test', 'level_1', 'level_2')

No comments:

Post a Comment