Notes on working with files and directories in Python
- http://docs.python.org/library/os.html#files-and-directories
- http://docs.python.org/library/os.path.html
- http://docs.python.org/library/shutil.html
- http://docs.python.org/library/glob.html
- http://docs.python.org/library/tarfile.html
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))
Related posts
- How to get the filename and it's parent directory in Python — posted 2011-12-28
- How to remove ^M characters from a file with Python — posted 2011-10-03
- Options for listing the files in a directory with Python — posted 2010-04-19
- Monitoring a filesystem with Python and Pyinotify — posted 2010-04-09
- os.path.relpath() source code for Python 2.5 — posted 2010-03-31
- A hack to copy files between two remote hosts using Python — posted 2010-02-08