Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from threading import Timer
- from os.path import isfile, join, exists
- import shutil, time
- #Constants
- PATH_TO_WATCH = "C:\\Users\\Angel\\Documents\\Programming\\Python\\files\\files"
- #Variables
- #FileReader class
- class FileReader:
- def __init__(self, path = None):
- self.path = path
- self.running = False
- self.timer = None
- def printFilesData(self, files):
- if self.path:
- #Create a timestamp for the folder that will hold our files
- timestamp = time.strftime("%Y%m%d%H%M%S")
- #Generate the path for the new folder
- destination = join(self.path, timestamp)
- for index, file in enumerate(files):
- #Check if the current file of the iteration is really a file
- if isfile(join(self.path, file)):
- #Call readAndMoveFile() method to print the file name, the data,
- #and and move the file to its destination.
- self.readAndMoveFile({"dest": destination, "name": file, "data": open(join(self.path, file))})
- def readAndMoveFile(self, fileData):
- print("\nName:%s\n\n%s\n" % (fileData["name"], fileData["data"].read()))
- #Important! Close the file, so we can move it, otherwise, we'll get an error that the file is in use.
- fileData["data"].close()
- #Create timestamped folder if not exists
- if not exists(fileData["dest"]):
- os.makedirs(fileData["dest"])
- try:
- #Move the file in
- shutil.move(join(self.path, fileData["name"]), fileData["dest"])
- print("\nFile \"%s\" moved to \"%s\" successfully.\n" % (fileData["name"], fileData["dest"]))
- except WindowsError as e:
- #If there is an error moving the file, will know here.
- print(e)
- def listFiles(self):
- if self.path:
- return [file for file in os.listdir(self.path)]
- return None
- def stopWatching(self):
- print("\nNot watching.\n")
- self.timer.cancel()
- def complete(self):
- #Timer finished.
- after = self.listFiles()
- added = [file for file in after if not file in self.lock]
- self.printFilesData(added)
- self.lock = after
- self.timer = Timer(5.0, self.complete)
- self.timer.start()
- def startWatching(self):
- if(self.path):
- self.lock = self.listFiles()
- print("\nWatching path %s...\n" % self.path)
- self.printFilesData(self.lock)
- self.timer = Timer(5.0, self.complete)
- self.timer.start()
- else: print("Path not set.")
- #Main class
- class Main():
- def __init__(self):
- #Create an instance of FileReader class, passing the path to watch as argument
- self.reader = FileReader(PATH_TO_WATCH)
- #Start watching the path
- self.reader.startWatching()
- if __name__ == '__main__':
- Main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement