python - 关于这个 python 脚本的问题!

标签 python

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/

相关文章:

python - 在 Matplotlib 寄生虫图中旋转 x 轴标签

python - 使用传统的 TCP 向 ZeroMQ 服务器发送消息,可能吗?

python - 思想树冠 : how do I add to the PATH?

python - Django 模型字段如何工作?

python - 路由器 cli 界面的 pxssh 登录问题

python - 为什么 requests 和 urllib2 缺少网页中的一些文本?

python - 即使经过数小时的训练,神经网络(从头开始,没有 tensorflow )也会给出错误的答案

python - 连接作为 python 中的类实例属性的 numpy 数组

python - 在 Python 中读取直接访问二进制文件格式

python - Altair 中的平行坐标