a question about this python script! -
if __name__=="__main__": fname= raw_input("please enter file:") mtrue=1 salaries='' salarieslist={} employeesdept='' employeesdeptlist={} try: f1=open(fname) except: mtrue=0 print 'the %s not exist!'%fname if mtrue==1: ss=[] x in f1.readlines(): if 'salaries' in x: salaries=x.strip() elif 'employees' in x: employeesdept=x.strip() f1.close() if salaries , employeesdept: salaries=salaries.split('-')[1].strip().split(' ') d in salaries: s=d.strip().split(':') salarieslist[s[0]]=s[1] employeesdept=employeesdept.split('-')[1].strip().split(' ') d in employeesdept: s=d.strip().split(':') employeesdeptlist[s[0]]=s[1] print "1) average salary in company: %s "%salarieslist['avg'] print "2) maximum , minimum salaries in company: maximum:%s,minimum:%s "%(salarieslist['max'],salarieslist['min']) print "3) how many employees there in each department :it:%s, development:%s, administration:%s"%( employeesdeptlist['it'],employeesdeptlist['development'],employeesdeptlist['administration']) else: print 'the %s data err!'%fname
when enter filename, didn't continue, why? if enter file named company.txt, show file not exist. why?
i can give hints can resolve problem better
create function , call in main e.g.
if __name__=="__main__": main()
don't put whole block under if mtrue==1:
instead return function on error e.g.
def main(): fname= raw_input("please enter file:") try: f1=open(fname) except: print 'the %s not exist!'%fname return ... # main code here
never catch exceptions , instead catch specific exception e.g. ioerror
try: f1 = open(fname): except ioerror,e: print 'the %s not exist!'%fname
otherwise catching exception may catch syntax error or mis-spelled names etc
print exception getting, may not file not found, may don't have read permission or that
and problem that, file may not exist, try input full path
Comments
Post a Comment