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
当我输入一个文件名,但它没有继续,为什么?如果我输入一个名为company.txt 的文件,但它总是显示该文件不存在。为什么?
最佳答案
我可以给你一些提示,帮助你更好地解决问题
创建一个函数并在 main 中调用它,例如
if __name__=="__main__":
main()
不要将整个 block 放在 if mTrue==1:
下,而只是在出错时从函数返回,例如
def main():
fname= raw_input("Please enter your file:")
try:
f1=open(fname)
except:
print 'The %s does not exist!'%fname
return
... # main code here
从不捕获所有异常,而是捕获特定异常,例如IO错误
try:
f1 = open(fname):
except IOError,e:
print 'The %s does not exist!'%fname
否则捕获所有异常可能会捕获语法错误或拼写错误的名称等
打印你得到的异常,它可能并不总是找不到文件,可能是你没有读取权限或类似的东西
最后你的问题可能只是,文件可能不存在,尝试输入完整路径
关于python - 关于这个 python 脚本的问题!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4190977/