2012-02-06 45 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 
相關問題