[Tutor] Advice on Strategy for Attacking IO Program

Saran Ahluwalia ahlusar.ahluwalia at gmail.com
Sun Mar 29 13:43:05 CEST 2015


Hello:

Here is what I am trying have my program do:


• Monitor a folder for files that are dropped throughout the day

• When a file is dropped in the folder the program should scan the file

o IF all the contents in the file have the same length

o THEN the file should be moved to a "success" folder and a text file
written indicating the total number of records processed

o IF the file is empty OR the contents are not all of the same length

o THEN the file should be moved to a "failure" folder and a text file
written indicating the cause for failure (for example: Empty file or line
100 was not the same length as the rest).


Below are the functions that I have been experimenting with. I am not sure
how to most efficiently create a functional program from each of these
constituent parts. I could use decorators (sacrificing speed) or simply
pass a function within another function.

[code]
import time
import fnmatch
import os
import shutil


#If you want to write to a file, and if it doesn't exist, do this:

if not os.path.exists(filepath):
    f = open(filepath, 'w')

#If you want to read a file, and if it exists, do the following:

try:
    f = open(filepath)
except IOError:
    print 'I will be moving this to the '


#Changing a directory to "/home/newdir"
os.chdir("/home/newdir")

def move(src, dest):
    shutil.move(src, dest)

def fileinfo(file):
    filename = os.path.basename(file)
    rootdir = os.path.dirname(file)
    lastmod = time.ctime(os.path.getmtime(file))
    creation = time.ctime(os.path.getctime(file))
    filesize = os.path.getsize(file)

    print "%s**\t%s\t%s\t%s\t%s" % (rootdir, filename, lastmod, creation,
filesize)

searchdir = r'D:\Your\Directory\Root'
matches = []

def search
for root, dirnames, filenames in os.walk(searchdir):
    ##  for filename in fnmatch.filter(filenames, '*.c'):
    for filename in filenames:
        ##      matches.append(os.path.join(root, filename))
        ##print matches
        fileinfo(os.path.join(root, filename))


def get_files(src_dir):
# traverse root directory, and list directories as dirs and files as files
    for root, dirs, files in os.walk(src_dir):
        path = root.split('/')
        for file in files:
            process(os.path.join(root, file))
                    os.remove(os.path.join(root, file))

def del_dirs(src_dir):
    for dirpath, _, _ in os.walk(src_dir, topdown=False):  # Listing the
files
        if dirpath == src_dir:
            break
        try:
            os.rmdir(dirpath)
        except OSError as ex:
            print(ex)


def main():
    get_files(src_dir)
    del_dirs(src_dir)


if __name__ == "__main__":
    main()


[/code]


More information about the Tutor mailing list