Ok, so I have the need to copy new files to a remote server. By default visual studio.net will copy everything under the sun, and that can take a little while over slow connections. So I wrote this script that compares the modification dates on two directory trees, and prompts the user for whether to overwrite the file or not.
Here's the code:
import os, stat, time, shutil, sys
#define the two directory trees
sourceBasePath = 'D:\\xxx'
destinationBasePath = 'I:\\xxx'
#go through all the directories and files in source tree
for root, dirs, files in os.walk(sourceBasePath):
for name in files:
#get the full path for this file
sourcePath = os.path.join(root, name)
#and on the remote server
destPath = sourcePath.replace(sourceBasePath, destinationBasePath)
#get the source date modified
sourceModifiedTime = os.stat(sourcePath)[stat.ST_MTIME]
if os.path.exists(destPath):
#if the file exists on the server, get it's time
destModifiiedTime = os.stat(destPath)[stat.ST_MTIME]
if sourceModifiedTime != destModifiiedTime:
#if they are different, display it
print ""
print sourcePath.replace(sourceBasePath, "")
print " Source = ", time.ctime(sourceModifiedTime)
print " Remote = ", time.ctime(destModifiiedTime)
#loop to get valid user input
overwrite = "asdf"
while(overwrite not in ('y','n','','q')):
overwrite = raw_input("Do you wish to overwrite this file? [y]/n/q? ")
if overwrite in ('y',''):
#copy the file and its stats, which will set the date modified on the remote
shutil.copyfile(sourcePath, destPath)
shutil.copystat(sourcePath, destPath)
print "Overwritten!"
elif overwrite == 'n':
print "Skipped."
elif overwrite == 'q':
sys.exit()
else:
#print an indication of a file that wasn't different
print ".",
else:
pass
Theres a little more I want to do with it:
- Keep a log of what files it overwrote
- Display some summary stats at the end
- Prompt to copy over files that don't exist in the destination, rather than just calling a
pass on that branch, which is effectively a NOP that exists so your formatting can be correct.
This introduces my first complaint with Python. I don't like an
else if structure having a keyword of
elif. I'm sure I'll get used to it, but that was something that annoyed me at first.
Looking at the
Python documentation, I found out that one of the Python slogans is "batteries included". It seems to be the case. Everything I wanted to do I could google and find the appropriate code snippet or built-in library documentation to handle it. Now the trick is to see if
Python for .NET is gonna work. :)