Notes on working with files and directories in Python
Documentation:- 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))
Post a comment
About
I'm Eliot and this is my notepad for programming topics such as Python, Django, Ubuntu, Emacs, etc... more »
Search Blog
Tags
-
algorithms
(4)
-
aws
(8)
-
blogproject
(20)
-
c_cplusplus
(12)
-
cardstore
(8)
-
colinux
(2)
-
concurrency
(9)
-
conkeror
(2)
-
cygwin
(18)
-
datastructures
(15)
-
datetime
(3)
-
dell
(3)
-
django
(39)
-
emacs
(20)
-
files_directories
(10)
-
install_setup
(7)
-
javascript
(3)
-
keyboard
(6)
-
matplotlib
(5)
-
mercurial
(4)
-
nginx
(2)
-
preferences
(8)
-
processes
(3)
-
pyqt
(18)
-
python
(122)
-
ratpoison
(3)
-
regexes
(5)
-
rsync
(3)
-
softwaretools
(17)
-
sql
(13)
-
ssh
(7)
-
subversion
(6)
-
twisted
(6)
-
ubuntu
(60)
-
urxvt
(5)
-
vxworks
(25)
-
webservices
(4)
-
wmii
(7)
Blogroll
- Adam Gomaa
- Alex Clemesha
- Amir Salihefendic
- Armin Ronacher
- David Beazley
- David Ziegler
- Duncan McGreggor
- Gareth Rushgrave
- Glyph Lefkowitz
- Guido van Rossum
- Ian Bicking
- Jacob Kaplan-Moss
- James Bennett
- James Tauber
- Jesper Noehr
- Matt Harrison
- Nikolay Kolev
- Parand Darugar
- Peter Baumgartner
- Peter Bengtsson
- Rob Hudson
- Simon Willison
- Will McGugan