Python Tutorial

Python Third-party Packages

File / Directory Handling

  • Checking existence of file or dir
    >>> import os.path
    # simply checking existence regardless type of file 
    >>> os.path.exists('/tmp')
    >>> os.path.exists('/tmps')
    # Checking if file exists. Not file or Not existing, then return False 
    >>> os.path.isfile('/tmps')
    # Checking if file exists. Not dir or Not existing, then return False
    >>> os.path.isdir('/tmps')
  • Delete files and dirs
    >>> import shutil
    # Delete an entire directory tree; path must point to a directory
    # OSError exception if not existing.
    >>> shutil.rmtree('/tmp/not_exists')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib64/python2.7/", line 239, in rmtree
        onerror(os.listdir, path, sys.exc_info())
      File "/usr/lib64/python2.7/", line 237, in rmtree
        names = os.listdir(path)
    OSError: [Errno 2] No such file or directory: '/tmp/not_exists'
    # no return value if successful.
    >>> print shutil.rmtree('/tmp/existing_dir') 

module behaviros


>>> import glob

# getting all files in /tmp/ in random order
>>> print glob.glob('/tmp/*')
# if dir doesn't exists, return empty list
>>> glob.glob('/tmp/not_exists')

How To

External References

Last modified 2 years ago Last modified on 01/29/18 04:03:30