Python filesystem

From wikinotes

Usage

expanding ~

os.path.expanduser('~/.vimrc')

move,delete

os.remove('/path/to/file')            # deletes file, or empty dir

shutil.rmtree('/path/to/directory')   # recursively deletes directory

os.listdir('/path/to/directory')      # list of filenames

test existence

os.path.exists('/path/to/anything')
os.path.isdir('/path/to/dir')
os.path.isfile('/path/to/file')
os.path.islink('/path/to/symlink')

permissions

os.chmod('/path', 0o755)
os.chown('/path', uid=1001, gid=1001)
os.access('/path', os.R_OK)

Test for current user's permissions:

perm_map = {
    0 : 'file does not exist: ',
    1 : 'current user does not have exec permissions to',
    2 : 'current user does not have write permissions to',
    3 : 'current user does not have write/exec permissions to',
    4 : 'current user does not have read permissions to',
    5 : 'current user does not have read/exec permissions to',
    6 : 'current user does not have read/write permissions to',
    7 : 'current user does not have read/write/exec permissions to',
}
if not os.access(path, permissions):
    raise OSError('{} "{}"'.format(perm_map[permissions], path))

file metadata

os.path.getmtime('/path/to/file')   # last modified time
os.path.getatime('/path/to/file')   # last accessed time
os.path.getsize('/path/to/file')    # size of file in bytes

current dir

os.getcwd()

partial paths

os.path.abspath('./dir')            # {CWD}/dir
os.path.basename( '/dir/file.txt')  # file.txt
os.path.dirname( 'dir/file.txt')    # dir

file objects

StringIO

StringIO fakes a file-descriptor. This is super useful.

Unfortunately reading from it is a bit strange...

import six
fd = six.StringIO()
fd.write('line\nline\nline')

file_contents = fd.getValue()
fd.close()