python,通过一个类从单独的文本文件中运行每一行

时间:2013-12-06 17:51:44

标签: python class

我想帮助弄清楚如何从文本文件到类中运行单独的行,这是我到目前为止所做的:

class Employee:
   'Class for all employees'
   empCount = 0

   def __init__(self, payNo, salary, job, mName, fName, sName):
      self.payNo = payNo
      self.salary = salary
      self.job = job
      self.mName = mName
      self.fName = fName
      self.sName = sName
      Employee.empCount += 1

   def displayCount(self):
     print ("Total Employee %d" % Employee.empCount)

   def displayEmployee(self):
      print ('{:<2s}{:<1}{:<13s}{:<15s}{:<7d}{:16s}{:>5s}{:<6d}'.format(self.sName,", ", self.mName, self.fName, self.payNo, self.job,"£",self.salary))
      ##print ('{:20s}{:20s}{:20s}'.format(self.sName,self.mName,self.fName))

"This would create first object of Employee class"
emp1 = Employee(12345, 2000, "Consultant", "Bartholomew", "Homer", "Simpson")
"This would create second object of Employee class"
emp2 = Employee(12346, 5000, "conultant in jobs","daniel", "matt", "li")
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee(s) %d" % Employee.empCount)

with open("emps.txt") as fileobject:
    for line in fileobject:
      print (line)

任何帮助将不胜感激,谢谢

1 个答案:

答案 0 :(得分:0)

有人可能会说这更像是“pythonic”

[('{4}, {5} {0} {2} ${1}'.format(*emp)) for emp in 
                 ((12345, 2000, "Consultant", "Bartholomew", "Homer", "Simpson"), 
                  (12346, 5000, "conultant in jobs","daniel", "matt", "li"))]

>>> ['Homer, Simpson 12345 Consultant $2000', 
     'matt, li 12346 conultant in jobs $5000']

如果此列表来自csv文件,您可以:

import csv
with open('in_file.csv') as in_file:
    for line in csv.reader(in_file):
        print '{4}, {5} {0} {2} ${1}'.format(*line)

有关货币符号,请参阅Currency formatting in Python