File

Snippets about files and folders manipulation.

check if file exists

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

import os.path
os.path.isfile(filename)

unicode (utf8) reading and writing to files

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

>>> import codecs
>>> f = codecs.open("test", "r", "utf-8")
>>> f.read()

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

os.getcwd()
os.path.dirname(os.path.realpath(__file__))

remove/delete a folder that is not empty

import shutil

shutil.rmtree('/folder_name')

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
487

reading binary file

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