Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

Notes on working with files and directories in Python

Documentation:

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

Documentation: http://docs.python.org/library/os.html#os.rename

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

How to imitate mkdir -p

import os
if not os.path.exists(directory):
    os.makedirs(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))

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Slicehost