关于这个python脚本的问题!

2024-09-27 00:11:43 发布

您现在位置: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

当我输入一个文件名,但它没有继续,为什么?如果我输入一个名为公司.txt,但它总是显示文件不存在。为什么?你知道吗


Tags: theinforiffnamef1splitstrip
3条回答

我可以给你一些提示,帮助你更好地解决问题

创建一个函数并在main中调用它

if __name__=="__main__":
    main()

不要将整个块放在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

从不捕获所有异常,而是捕获特定的异常,例如IOError

try:
   f1 = open(fname):
except IOError,e:
  print 'The %s does not exist!'%fname

否则捕获所有异常可能会捕获语法错误或名称拼写错误等

打印您遇到的异常,可能不总是找不到文件,可能是您没有读取权限或类似的权限

最后,您的问题可能只是,文件可能不存在,请尝试输入完整路径

除了更具体地说明要捕获哪些异常外,还应考虑捕获异常对象本身,以便可以打印它的字符串表示形式作为错误消息的一部分:

try:
    f1 = open(fname, 'r')
except IOError, e:
    print >> sys.stderr, "Some error occurred while trying to open %s" % fname
    print >> sys.stderr, e

(您还可以了解有关异常对象的特定类型的更多信息,也许还可以处理 代码中的一些异常。您甚至可以从解释器中捕获异常以供自己检查,这样就可以对它们运行dir(),并对找到的每个有趣的属性运行type()。。。等等。你知道吗

当前工作目录不包含company.txt。 设置当前工作目录或使用绝对路径。你知道吗

您可以这样更改工作目录:

import os
os.chdir(new_path)

相关问题 更多 >

    热门问题