if __name__=="__main__":
fname= raw_input("Please enter your file:")
mTrue=1
Salaries=''
Salarieslist={}
Employeesdept=''
Employeesdeptlist={}
try:
f1=open(fname)
except:
mTrue=0
print 'The %s does not exist!'%fname
if mTrue==1:
ss=[]
for x in f1.readlines():
if 'Salaries' in x:
Salaries=x.strip()
elif 'Employees' in x:
Employeesdept=x.strip()
f1.close()
if Salaries and Employeesdept:
Salaries=Salaries.split('-')[1].strip().split(' ')
for d in Salaries:
s=d.strip().split(':')
Salarieslist[s[0]]=s[1]
Employeesdept=Employeesdept.split('-')[1].strip().split(' ')
for d in Employeesdept:
s=d.strip().split(':')
Employeesdeptlist[s[0]]=s[1]
print "1) what is the average salary in the company: %s "%Salarieslist['Avg']
print "2) what are the maximum and minimum salaries in the company: maximum:%s,minimum:%s "%(Salarieslist['Max'],Salarieslist['Min'])
print "3) How many employees are there in each department :IT:%s, Development:%s, Administration:%s"%(
Employeesdeptlist['IT'],Employeesdeptlist['Development'],Employeesdeptlist['Administration'])
else:
print 'The %s data is err!'%fname
当我输入一个文件名,但它没有继续,为什么?如果我输入一个名为公司.txt,但它总是显示文件不存在。为什么?你知道吗
我可以给你一些提示,帮助你更好地解决问题
创建一个函数并在main中调用它
不要将整个块放在
if mTrue==1:
下,而只需在出错时从函数返回从不捕获所有异常,而是捕获特定的异常,例如IOError
否则捕获所有异常可能会捕获语法错误或名称拼写错误等
打印您遇到的异常,可能不总是找不到文件,可能是您没有读取权限或类似的权限
最后,您的问题可能只是,文件可能不存在,请尝试输入完整路径
除了更具体地说明要捕获哪些异常外,还应考虑捕获异常对象本身,以便可以打印它的字符串表示形式作为错误消息的一部分:
(您还可以了解有关异常对象的特定类型的更多信息,也许还可以处理 代码中的一些异常。您甚至可以从解释器中捕获异常以供自己检查,这样就可以对它们运行
dir()
,并对找到的每个有趣的属性运行type()
。。。等等。你知道吗当前工作目录不包含
company.txt
。 设置当前工作目录或使用绝对路径。你知道吗您可以这样更改工作目录:
相关问题 更多 >
编程相关推荐