Skip to main content
 首页 » 编程设计

python之'try.....except' 的问题引发 ROOT 文件的语法错误

2025年05月04日22zhengyun_ustc

我正在尝试在目录中查找损坏的根文件。基本上,我的代码抛出 SyntaxError: invalid syntax when trying the following

import ROOT as root 
import sys 
import glob 
 
 
dir=sys.argv[1] 
txtfiles = [] 
for file in glob.glob(dir+"/*.root"): 
    f = root.TFile(file,'r') 
    try : 
        myTree = f.Get("AC1B") 
 
        except IOError: 
            print 'this is not good',f 
            continue 
        else : 
            print 'the filename is ',file, myTree.GetEntries() 

我也尝试过 except: 但这也行不通。

请您参考如下方法:

您的 except 语句必须与 try 处于同一缩进级别。它目前嵌套在 try 中:

import ROOT as root 
import sys 
import glob 
 
 
dir = sys.argv[1] 
txtfiles = [] 
for file in glob.glob(dir + "/*.root"): 
    f = root.TFile(file,'r') 
    try: 
        myTree = f.Get("AC1B") 
 
    except IOError: 
        print 'this is not good',f 
        continue 
    else: 
        print 'the filename is ',file, myTree.GetEntries()