Python Watch file directory

Source: Internet
Author: User

This example is to use watchdog to monitor the new file, when the new file, call the corresponding parsing script, to parse the library.

Directory:

-scripts

--Script 1.py

--Script 2.py

-tmp

--Processed Files 1,

--Processed Files 2

config.py

watchdog.py


The watchdog.py file, which only listens for events created by new files:

# coding=utf8import sysimport timeimport loggingimport impimport reimport  Scripts. configfrom watchdog.observers import observerfrom watchdog.events import  loggingeventhandlerfrom watchdog.events import filesystemeventhandlerclass  Createdeventhandler (FileSystemEventHandler):     def __init__ (self):         filesystemeventhandler.__init__ (self)     def on_created (handler,event):        file_name = event.src_path[2:]         print  '---' +file_name         moduleName =  '         for key in parse _map.keys ():             if (Re.match (Key,file_name) ):                modulename = parse_map[key]                 break         if (modulename !=  "):             try:                  #动态加载相应的module                  parsemodule =  imp.load_module (ModuleName,*imp.find_module ( modulename,['./scripts/'))                  print  '   load module:  '  + moduleName                 parsemodule.parse (file_name)             except exception,e:                 print e# matches the file match to the corresponding parsing script parse_map={              ' ^test.xlsx$ ': ' Test ',              ' ^emt_finance.*\.xlsx ': ' Emt_finance '}if __name__ ==   "__main__":     logging.basicconfig (level=logging.info, format= '% (asctime) s  - % (message) s ', datefmt= '%y-%m-%d %h:%m:%s ')     path = sys.argv[1 ] if len (SYS.ARGV)  > 1 else  '. '     event_handler = createdeventhandler ()     observer =  observer ()     observer.schedule (Event_handler, path, recursive=false)     observer.start ()     print  ' WatChing '     try:        while True:             time.sleep (1)     except  keyboardinterrupt:        observer.stop ()      observer.join ()


Parsing script test.py

# filename: test.py# a simple test code import xlrdimport  Mysqldbimport datetimeimport osimport statimport shutildef parse (file):     values = []    if (File.split ('. ') [-1] !=  ' xlsx '):        print  '---skip '  +  file        return    try:         data = xlrd.open_workbook (file)          table = data.sheets () [0]        for i in  range (1,table.nrows):             row =  table.row_values (i)              #excel   Date is the days from 1899/12/30 &nbSp;          row[0] = datetime.date (1899,12,30)  + datetime.timedelta (row[0])              values.append (Row)     except Exception,e:         print e     #print  values    try:         conn = mysqldb.connect (Config.mysql_host,config.mysql_user, CONFIG.MYSQL_PASSWD, ' Test ', Config.mysql_port)         cur =  Conn.cursor ()          #values [0][5]=4         for v in values:             count = cur.execute (' Replace into testtable values (%s,%s,%s,%s,%s,%s) ', V)          conn.commit ()         print  '   parse  Complete. '          '         results= Cur.fetchmany (5)         for r in results:             print r          "        cur.close ()          conn.close ()          #os. Remove (' Tmp/test.pyc ')                  if (os.path.exists (' tmp/' + File):             os.chmod (' tmp/' +file,stat. S_iwrite) #去掉只读属性             os.remove (' tmp/' +file)   #删除它 &nbsP;       shutil.move (file, ' tmp/')          print  '   move filt to temp:  '  + file         print  '   success! '                 except  mysqldb.error,e:        print  "Mysql Error %d: %s"  %  (e.args[0], e.args[1]) if __name__ ==  ' __main__ ':     exec   "Import config as config"     print  ' = = ' *10      #os. Remove ('.. /tmp/test.xlsx ')      #shutil. Move (' ... /test.xlsx ', ' tmp/')      #parse (' ... /test.xlsx ') else:    exec  "import scripts. Config as config "


Python Watch file directory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.