Monday 8 April 2019

Python OS module in detail with examples & syntax

__author__ = "Narendra Boyina"

"""
The OS module allows us to interact with the underlying operating system in several different ways.
- Navigate the file system
- Get file information
- Look up and change the environment variables- Move files around
- Many moreTo begin, import the os module. This is a built in module, 
no third party modules need to be installed.
"""

import os,time
from datetime import datetime

"""dir() will display all of the methods and attributes  of os module"""
# print(dir(os))

"""To get current working directory"""
# path = os.getcwd()  # @Answer /home/narendrab/Python/My Practice# print(path)

"""To Change directory, from one path to another path. this requires a path to change to
Syntax ==> os.chdir(path)"""
# path = "/home/narendrab/pytest"# os.chdir(path)
# print(os.getcwd())  # will display  /home/narendrab/pytest


# To print list of directories & files names in provided path,
# Syntax ==> os.listdir(path) but by default path is in the current directory
# print(os.listdir("/home/narendrab/Python/"))

# To create a new directory. Syntax ==> mkdir("Directory/folder name")
# os.mkdir("Narendra")


# if you want to create multiple directories at once
# (directory inside directory inside directory ..ectc)
# Syntax ==> os.makedirs("directory_Name/Sub_directory_1/Sub_directory_2")
# os.makedirs("Narendra/Bhagyasree/Raj")



# Remove single directory/ multiple directories
# Syntax ==> os.rmdir(file)


# Dirs created ==>path changed ==>printed path after changed==> came back one stepDir
# path = "Narendra/Bhagyasree/Raj"
# os.makedirs(path)  
# creation of directories/sub-dir
# print("Directories were created just check in PWD/(Pycharm tree structure)")
## os.chdir(path)  # enter in to the directories created just now
# print(os.getcwd())  # will display PWD
## os.chdir("/home/narendrab/Python/My Practice/Narendra/Bhagyasree")
# come back without giving path
# os.rmdir("Raj")  # Removes the last directory in the path
# print(os.getcwd())

# # Syntax ==> removedirs(file)  # Removes intermediate directories if specified

# create a file with write mode
# fp=open("test.txt", "w+")
# fp.write("Hi,\n This file was created just for execution purpose")
# fp.close()


# # Rename a file or folder
# os.rename("test.txt","Narendra.txt")  # This renames text.txt to Narendra.txt
## # Look at info about files# print(os.stat("Narendra.txt"))
# # Useful stat results: st_size (bytes), st_mtime (time stamp)
# print(os.stat("Narendra.txt").st_size)  # display size of the file
# print(os.stat("Narendra.txt").st_mtime)  # display the last modification time of the file (but can't understand by user)
# last_mod_time = os.stat("Narendra.txt").st_mtime
# print(datetime.fromtimestamp(last_mod_time))  # Now user can understand recently file modified time




# # To see entire directory tree and files within
# os.walk is a generator that yields a tuple of 3 values as it walks the directory tree
# path = os.getcwd()
# # for dirpath, dirnames,filenames in os.walk(path):
#     print("current path : ",dirpath)
#     print("Directories : ",dirnames)
#     print("Files: ",filenames)
#     print("***************************************")


# # # This is useful for locating a file that you can’t remember where it was
# If you had a web app, and you wanted to keep track of the file info within a certain directory structure,
# then you could to thru the os.walk method and go thru all files and folders and collect file information.
#  # Access home directory location by grabbing home environment variable
# X = os.environ.get("HOME") # Returns a home directory path of the user
# print(X)  # /home/narendrab




# # # # # To properly join two files together use os.path.join(). & will be inserted one slash
# # file_path = os.path.join(os.environ.get("HOME"), "test.txt")

# # # # the benefit of os.path.join, is it takes the guess work out of inserting a slash
# # print(file_path)  # /home/narendrab/test.txte as a tuple
## os.path.exists("/tmp/test.txt")# # returns a boolean
## os.path.isdir("/tmp/test.txt")# # returns False
## os.path.isfile("/tmp/test.txt")# # returns True
## os.path.splitext("/tmp/test.txt")# # Splits file route of the path and the extension
# # returns ("/tmp/test", ".txt")# # This is alot easier than parsing out the extension. 
Splitting off and taking the first value is much better.



# # Very useful for file manipulation

# os.path has other useful methods
## os.path.basename# # This will grab filename of any path we are working on
## os.path.dirname("/tmp/test.txt")# # returns the directory /tmp
## os.path.split("/tmp/test.txt")# # returns both the directory and the fil



"""We can find out, From the root path(provided by user) 
what are the files (.txt/.py/.doc)available in each sub-folders.  """
import os

# path = "/home/narendrab/Python"
# for root,subdir,files in os.walk(path):
# # we can find-out .py files available in each subdirectory from provided root directory
##  for file in files:
#     if file.endswith(".txt"):
#        print("FileName ==> {}".format(os.path.join(root,file)))

## # same like above we can find-out .py files available in each subdirectory from provided root directory
##  for file in files:
#     if file.endswith(".py"):
#        print("FileName --> %s" %(os.path.join(root,file)))
def get_files_based_(path, extension):
for root, subdir, files in os.walk(path):
for file in files:
if file.endswith(extension):
print("FileName %s" % (os.path.join(root, file)))

# get_files_based_(path, ".txt")

                                Request: Please provide your valuable comments

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete