Snippets about files and folders manipulation.

check if file exists

If you need to be sure it’s a file:

import os.path

unicode (utf8) reading and writing to files

It is easier to use the open method from the codecs module:

>>> import codecs
>>> f ="test", "r", "utf-8")

extracting extension from filename

import os
filename, ext = os.path.splitext('/path/to/somefile.ext')

get file creation & modification date/times

ctime() does not refer to creation time on *nix systems, but rather the last time the inode data changed:

import os.path, time
print "last modified: %s" % time.ctime(os.path.getmtime(file))
print "created: %s" % time.ctime(os.path.getctime(file))

find current directory and file’s directory


remove/delete a folder that is not empty

import shutil


recursively walk a directory

import os
root = 'your root path here'

# dirs are the directory list under dirpath
# files are the file list under dirpath
for dirpath, dirs, files in os.walk(root):
    for filename in files:
        fullpath = os.path.join(dirpath, filename)
        print fullpath

get file size

>>> import os
>>> statinfo = os.stat('index.rst')
>>> statinfo.st_size

reading binary file

with open("myfile", "rb") as f:
    byte =
    while byte:
        # Do stuff with byte.
        byte =