SaltyCrane Blog — Notes on JavaScript and web development

Notes on working with files and directories in Python


How to list files in a directory

See my separate post: How to list the contents of a directory with Python

How to rename a file: os.rename


import os
os.rename("/tmp/oldname", "/tmp/newname")

How to imitate mkdir -p

import os
if not os.path.exists(directory):

How to imitate cp -r (except copy only files including hidden dotfiles)

What didn't work for my purpose:

import os

def _copy_dash_r_filesonly(src, dst):
    """Like "cp -r src/* dst" but copy files only (don't include directories)
    (and include hidden dotfiles also)
    for (path, dirs, files) in os.walk(src):
        for filename in files:
            srcfilepath = os.path.join(path, filename)
            dstfilepath = os.path.join(dst, os.path.relpath(srcfilepath, src))
            dstdir = os.path.dirname(dstfilepath)
            if not os.path.exists(dstdir):
                run('mkdir -p %s' % dstdir)
            run('cp -f %s %s' % (srcfilepath, dstfilepath))