Table of Contents

Python basic examples

Python processing file and directory

os package

os.path basic functions

os.path custom examples

Get all files and directories in current directory

Get Path of execute file

import os
 
fullpathexecute = sys.argv[0]
pathofexecute = os.path.split(fullpathexecute)[0]
print pathofexecute

Read and Update File

with open(filename, "rb") as f:
   content = f.read()
if content != "":
   #content = content.replace(oldstring, newstring)
   with open(filename, "wb") as f:
      f.write(content)

Python Command Line Arguments

refer: https://www.tutorialspoint.com/python/python_command_line_arguments.htm

Consider we want to pass two file names through command line and we also want to give an option to check the usage of the script. Usage of the script is as follows −

usage: test.py -i <inputfile> -o <outputfile>

Here is the following script to test.py −

#!/usr/bin/python
 
import sys, getopt
 
def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile
 
if __name__ == "__main__":
   main(sys.argv[1:])

Now, run above script as follows −