User Tools

Site Tools


python:pythonbasicexamples

Python basic examples

Python processing file and directory

os package

  • Executing a shell command
    os.system()
  • Get the users environment
    os.environ()
  • Returns the current working directory
    os.getcwd()
  • Return a list of the entries in the directory given by path
    os.listdir(path)
  • Create a directory named path with numeric mode mode
    os.mkdir(path)
  • Recursive directory creation function
    os.makedirs(path)
  • Remove (delete) the file path
    os.remove(path)
  • Remove directories recursively
    os.removedirs(path)
  • Rename the file or directory src to dst
    os.rename(src, dst)
  • Remove (delete) the directory path
    os.rmdir(path)

os.path basic functions

  • split:
    import os
    from urlparse import urlparse
     
    filename = "E:\\do-choi\\do-choi-giay\\the-hinh-chu-so-vua-hoc-vua-choi.html"
     
    print "full filename", filename
    print "using", os.name, "..."
    print "split", "=>", os.path.split(filename)
    print "splitdrive", "=>", os.path.splitdrive(filename)
    print "splitext", "=>",os.path.splitext(filename)
    print "splitunc", "=>",os.path.splitunc(filename)

    output:

    full filename E:\do-choi\do-choi-giay\the-hinh-chu-so-vua-hoc-vua-choi.html
    using nt ...
    split => ('E:\\do-choi\\do-choi-giay', 'the-hinh-chu-so-vua-hoc-vua-choi.html')
    splitdrive => ('E:', '\\do-choi\\do-choi-giay\\the-hinh-chu-so-vua-hoc-vua-choi.html')
    splitext => ('E:\\do-choi\\do-choi-giay\\the-hinh-chu-so-vua-hoc-vua-choi', '.html')
    splitunc => ('', 'E:\\do-choi\\do-choi-giay\\the-hinh-chu-so-vua-hoc-vua-choi.html')
  • using os.path to check what a filename represents
    import os
     
    FILES = (
        os.curdir,
        "/",
        "file",
        "/file",
        "samples",
        "samples/sample.jpg",
        "directory/file",
        "../directory/file",
        "/directory/file"
        )
     
    for file in FILES:
        print file, "=>",
        if os.path.exists(file):
            print "EXISTS",
        if os.path.isabs(file):
            print "ISABS",
        if os.path.isdir(file):
            print "ISDIR",
        if os.path.isfile(file):
            print "ISFILE",
        if os.path.islink(file):
            print "ISLINK",
        if os.path.ismount(file):
            print "ISMOUNT",
        print

    output:

    . => EXISTS ISDIR
    / => EXISTS ISABS ISDIR ISMOUNT
    file =>
    /file => ISABS
    samples => EXISTS ISDIR
    samples/sample.jpg => EXISTS ISFILE
    directory/file =>
    ../directory/file =>
    /directory/file => ISABS

os.path custom examples

  • Using os.path to handle filename
    import os
    import re
     
    filename = "my/little/pony.txt"
     
    print "using", os.name, "..."
    print "split", "=>", os.path.split(filename)
    print "splitext", "=>", os.path.splitext(filename)
    print "dirname", "=>", os.path.dirname(filename)
    print "basename", "=>", os.path.basename(filename)
    print "join", "=>", os.path.join(os.path.dirname(filename),
                                     os.path.basename(filename))
    print "realpath", os.path.realpath(filename)
    print "abspath", os.path.abspath(filename)
    print "rename filename to ", re.sub(r'\.txt', '', filename) + '.html'

    ⇒ output

    using nt ...
    split => ('my/little', 'pony.txt')
    splitext => ('my/little/pony', '.txt')
    dirname => my/little
    basename => pony.txt
    join => my/little\pony.txt
    realpath E:\backup\GoogleDrive\projects\python\my\little\pony.txt
    abspath E:\backup\GoogleDrive\projects\python\my\little\pony.txt
    rename filename to  my/little/pony.html
  • get normal path
    import os
     
    filename = "E:\\do-choi\\do-choi-giay\\the-hinh-chu-so-vua-hoc-vua-choi.html"
     
    print "full filename", filename
    print "basename", os.path.basename(filename)
    print "dirname", os.path.dirname(filename)
    print "splitdrive", "=>", os.path.splitdrive(filename)
    fullpathname = os.path.dirname(filename)
    pathname = os.path.splitdrive(fullpathname)[1]
    print "pathname = ", pathname
    normalpath = pathname[1:]
    print "normalpath = ", normalpath

    output:

    full filename E:\do-choi\do-choi-giay\the-hinh-chu-so-vua-hoc-vua-choi.html
    basename the-hinh-chu-so-vua-hoc-vua-choi.html
    dirname E:\do-choi\do-choi-giay
    splitdrive => ('E:', '\\do-choi\\do-choi-giay\\the-hinh-chu-so-vua-hoc-vua-choi.html')
    pathname =  \do-choi\do-choi-giay
    normalpath =  do-choi\do-choi-giay
  • urlparse
    import os
    from urlparse import urlparse
     
    url = "http://shop.babies.vn/do-choi/do-choi-giay/the-hinh-chu-so-vua-hoc-vua-choi.html"
    o = urlparse(url)
    print o
    filename = o.path
    print filename
    print "split", "=>", os.path.split(filename)
    print "splitext", "=>", os.path.splitext(filename)
    print "dirname", "=>", os.path.dirname(filename)
    print "basename", "=>", os.path.basename(filename)
    print "join", "=>", os.path.join(os.path.dirname(filename),
                                     os.path.basename(filename))
    print "realpath", os.path.realpath(filename)
    print "abspath", os.path.abspath(filename)

    output:

    ParseResult(scheme='http', netloc='shop.babies.vn', path='/do-choi/do-choi-giay/the-hinh-chu-so-vua-hoc-vua-choi.html', params='', query='', fragment='')
    /do-choi/do-choi-giay/the-hinh-chu-so-vua-hoc-vua-choi.html
    split => ('/do-choi/do-choi-giay', 'the-hinh-chu-so-vua-hoc-vua-choi.html')
    splitext => ('/do-choi/do-choi-giay/the-hinh-chu-so-vua-hoc-vua-choi', '.html')
    dirname => /do-choi/do-choi-giay
    basename => the-hinh-chu-so-vua-hoc-vua-choi.html
    join => /do-choi/do-choi-giay\the-hinh-chu-so-vua-hoc-vua-choi.html
    realpath E:\do-choi\do-choi-giay\the-hinh-chu-so-vua-hoc-vua-choi.html
    abspath E:\do-choi\do-choi-giay\the-hinh-chu-so-vua-hoc-vua-choi.html

Get all files and directories in current directory

  • using os.path.walk list all file in current directory and all subdirectories
    import os
     
    def gotodir(arg, directory, files):
        for file in files:
            print file
     
    os.path.walk(".", gotodir, "")

    Output

    .project
    .pydevproject
    conent.tpl
    index.html
    parser.py
    test.py
  • using os.path.walk list all full filename in current directory and all subdirectories
    import os
     
    def gotodir(arg, directory, files):
        for file in files:
            fullfilename = os.path.join(directory,file)
            print fullfilename
     
    os.path.walk(".", gotodir, "")
  • Find all files with extension “.py”:
    import os
     
    def gotodir(arg, directory, files):
        for file in files:
            extName = os.path.splitext(file)[1];
            if extName == '.py':
                fullfilename = os.path.join(directory,file)
                print fullfilename
     
    os.path.walk(".", gotodir, "")

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 −

  • Option1:
    $ test.py -h

    output:

    test.py -i <inputfile> -o <outputfile>
  • Option2:
    $ test.py -i inputfile

    output:

    Input file is " inputfile
    Output file is "
python/pythonbasicexamples.txt · Last modified: 2022/10/29 16:15 by 127.0.0.1