Ways to Move up and Down the dir structure in Python
#Moving up/down dir str开发者_JS百科ucture
print os.listdir('.')
print os.listdir('..')
print os.listdir('../..')
Any othe ways??? I got saving dirs before going deeper, then reassigning later.
This should do the trick:
for root, dirs, files in os.walk(os.getcwd()):
for name in dirs:
try:
os.rmdir(os.path.join(root, name))
except WindowsError:
print 'Skipping', os.path.join(root, name)
This will walk the file system beginning in the directory the script is run from. It deletes the empty directories at each level.
Of course there are -
thre are both os.walk
- which returns tuples with the subdirectories, and the files tehrein as
os.path.walk
, which takes a callback function to be called for each file in a directory structure.
You can check the online help for both functions.
You can use os.chdir()
http://docs.python.org/library/os.html#os-file-dir
Am I missing something in the question?
"and what if you wanted to move all the files up to the root directory?"
You could do something like:
for root, dirs, files in os.walk(os.getcwd()):
for f in files:
try:
shutil.move(os.path.join(root, f), os.getcwd())
except:
print f, 'already exists in', os.getcwd()
精彩评论