More os and shutil Examples

If manipulating files and directories is your need

os and shutil are your speed, indeed!

You might as well come to grips with the fact that to do much in the way of file and directory manipulation you are going to have to use both the os module and the shutil module.  What kills most folks getting started is the exact path syntax.  These modules are extensive – the following code just hits the high points as examples.  This code assumes you have a D: drive on which there is a \temp folder.  This all works in windows but I have not tested it in Linux yet.


import os
import shutil
#get the current working directory
workingDir=os.getcwd()
print('working directory: '+ workingDir)

#change dirctory - will not effect the drive
newDir = "/temp"
os.chdir(newDir)
print('changed directory to: '+ os.getcwd())

#find out what is in the current directory
dirlist = os.listdir()
print('current directory contents: ', dirlist)

print('make a new directory in current path - making "tempLevel2"')
os.mkdir("tempLevel2")
print('now we have:')
print(os.listdir())

print('rename our new directory to "tempNewName"')
os.rename('tempLevel2','tempNewName')
print('and we have:')
print(os.listdir())

# move deleteme.txt to the tempNewName directory
shutil.move("deleteme.txt","/temp/tempNewName/") #be very careful of exact path syntax

print('Temp directory: ' )
print(os.listdir())

print('tempNewName directory:')
newDir="/temp/tempNewName"
os.chdir(newDir)
print(os.listdir())

#copy the file deleteme as deletemeCopy
shutil.copyfile("deleteme.txt", "deletemeCopy.txt")
print ('file copied and given new name')
print(os.listdir())

#delete the original
print ('now delete the original')
os.remove("deleteme.txt")
print(os.listdir())