2012-02-06 59 views
0

我写这一小段代码: 我想在re.match的情况下,处理异常返回null

import csv 
import re 
import os 
fileobj = csv.reader(open('c:\\paths1.csv', 'rb'), delimiter=' ', quotechar='|') 
for row in fileobj: 
    for x in row: 
     with open(x) as f: 
      for line in f: 
       if re.match('(.*)4.30.1(.*)', line): 
        print 'The version match: '+ line 

        print 'incorrect version'  
     filesize= os.path.getsize(x) 


    print 'The file size is :'+ str(filesize) +' bytes'; 

我想什么让它做的是:

添加异常处理,因为据我所知,如果match()没有 匹配什么文件中该方法返回的值None,但我不明白 如何读取值作一比较,让脚本打印(版本不匹配)...

任何人有任何建议吗?将某些Web文档链接到一起也不错。

预先感谢您!

回答

2

你是在正确的道路。由于None布尔值是假,所有你需要做的就是在代码中使用的else分支:

if re.match('(.*)4.30.1(.*)', line): 
      print 'The version match: '+ line 
else: 
      print 'incorrect version' 

现在我敢肯定你要么要匹配的第一个(包含版本号的那个)该文件或整个文件的行,所以以防万一:

 #first line 
     with open(x) as f: 
      try: 
       #next(f) returns the first line of f, you have to handle the exception in case of empty file 
       if re.match('(.*)4.30.1(.*)', next(f))): 
        print 'The version match: '+ line 
       else: 
        print 'incorrect version' 
      except StopIteration: 
       print 'File %s is empty' % s 


     #anything 
     with open(x) as f: 
      if re.match('(.*)4.30.1(.*)', f.read())): 
       print 'The version match: '+ line 
      else: 
       print 'incorrect version' 
+0

非常感谢!!!!我也曾尝试类似的东西,但我不认为它可能是直截了当的:)我喜欢蟒蛇(我以前在Turbo Pascal的编程) – nassio 2012-02-06 10:48:02

+0

-1。如果没有任何行匹配,OP想要打印“不正确的版本”。此代码将在每个不匹配的行上打印一次。 – 2012-02-06 10:54:23

+0

@JohnMachin是的,他也说,'match'返回时没有不匹配的文件** **东西,然后匹配agains ** **行,所以它不是至少并不清楚OP真正想要的。 – soulcheck 2012-02-06 10:58:43

0
>>> st = "hello stackers" 
>>> pattern = "users" 
>>> if re.match(pattern,st): 
...  print "match found" 
... else: 
...  print "no match found" 
... 
no match found 
>>> 

因为re.match()回报true如果比赛found.So,只需使用一个else statement如果no找到匹配。

+0

非常感谢这就是我不能在网络 – nassio 2012-02-06 10:49:08

+0

-1上找到。如果没有任何行匹配,OP想要打印“不正确的版本”。此代码将在每个不匹配的行上打印一次。 – 2012-02-06 10:55:17

1
import csv 
import re #### don't need it 
import os #### don't need it 
fileobj = csv.reader(open('c:\\paths1.csv', 'rb'), delimiter=' ', quotechar='|') 
for row in fileobj: 
    for x in row: 
     with open(x) as f: 
      for line in f: 
       if '4.30.1' in line: #### much simpler than regex 
        print 'The version match: '+ line 
        break 
      else: # Yes, a `for` statement can have an `else:` 
       # end of file, "break" doesn't arrive here 
       print 'incorrect version' # done ONCE at end of file 
相关问题