fileOrganizer.py
import shutil
import os
import stat
import time
def run(directory):
"""
Scans a directory of files and creates a folder for each day a file was last modified.
The script then copies the file into that directory.
Parameters:
directory - Directory to scan.
Returns:
Nothing.
"""
# The os.walk function is used to traverse file directories
for root, directories, files in os.walk(directory):
# Loops through each file
for image in files:
# Create the full path to the file
imageFilePath = os.path.join(root, image)
# Get the date the file was last modified
date = time.localtime(os.stat(imageFilePath)[stat.ST_MTIME])
# Extract out the year, month and day from the date
year = date[0]
month = date[1]
day = date[2]
# Form the directory name as yyyymmdd
dateDirectory = os.path.join(root, '%d%02d%02d' % (year, month, day))
# Create the directory is it does not exist
if not os.path.exists(dateDirectory):
os.mkdir(dateDirectory)
print 'Made directory: %s' % dateDirectory
# Form the full path to where we want to copy the file
newFilePath = os.path.join(root, '%s\\%s' % (dateDirectory, image))
# Copy the file
shutil.copy2(imageFilePath, newFilePath)
print 'Copied %s to %s' % (imageFilePath, newFilePath)
Concepts used: functions, lists, for loops, conditional statements, string formatting, exceptions.
Python Outside of Maya Conclusion
We have now covered enough Python to begin scripting in Maya. Believe it or not, you have also learned about 75% of the syntax of most other scripting and programming languages. Most other languages have the same concepts like while and for loops, if/else statements, functions, lists, math operators, etc. There are however, many aspects of Python that we have not covered. If you really want to do some advanced scripts or design some advanced systems, I highly recommend studying more about Python in books and online.
