Python - File Processing

From PeformIQ Upgrade
Jump to navigation Jump to search

Here is a fragment of code with some simple file parsing logic...

#---------------------------------------------------------------------

def analyse(logfile):
   cnt = 0

   lfd     = open(logfile, 'r')

   for line in lfd.readlines():
      if cnt == 11:
         response_xml = line[:-1]
         print "[[%s]]" % response_xml
      print "Cnt -> %d" % cnt
      cnt += 1

   lfd.close()

   ofd = open('response.xml', 'w')

   ofd.write(response_xml)
   ofd.close()

   return response_xml

#---------------------------------------------------------------------

And another approach:

#---------------------------------------------------------------------

def readConfig():
   global tableCnt
   global tables

   try:
      f = open(FILE, 'r')
   except IOError, e:
      sys.stderr.write(FILE + ': cannot open: ' + `e` + '\n')
      sys.exit(1)

   dataFlg = 0

   while 1:
      line = f.readline()

      if not line: break

      line = line.strip()

      if (line.find("MailDir") != -1):
         data     = line.split("=")
         mailDir  = data[1].strip()

      elif (line.find("User") != -1):
         data     = line.split("=")

         (name, passwd, dirName) = data[1].split(",")

         name     = name.strip()
         passwd   = passwd.strip()
         dirName  = dirName.strip()
         wrkDir   = mailDir + "/" + dirName

         user     = User(name, passwd, wrkDir)

         print "Adding user %s - %d messages" % (name, len(user.Messages))

         users[name] = user

   f.close()

   print "Added %d users" % len(users)

#---------------------------------------------------------------------