2012-04-26 14 views
0

好吧,我有這個簡單的代碼來繪製簡單的等高線圖:Python和MatPlotlib:ValueError異常和skip_header

try: 
    header = input("\nEnter the number of rows to skip for the text file's header: ") 
except (NameError, SyntaxError, TypeError, ValueError) as e: 
    print 'This is not a valid integer. This program will be terminated.' 
    sys.exit(0) 

z = np.genfromtxt(mapdocument.txt,skip_header= header) 
(rows,cols) = z.shape 

pyplot.figure() 
pyplot.contour(x, y, z, 10) 
pyplot.show() 

比方說skip_header應該是5,我想知道我應該怎麼做,以避免從末崩潰的程序,如果用戶輸入大於5

以外的值。這是我得到的錯誤:

Traceback (most recent call last): 
    File "F:\sampletask1.py", line 134, in <module> 
    z = np.genfromtxt(filename,skip_header= header) 
    File "C:\Python_1\lib\site-packages\numpy\lib\npyio.py", line 1560, in genfromtxt 
    raise ValueError(errmsg) 
ValueError: Some errors were detected ! 
    Line #9 (got 348 columns instead of 2) 
    Line #10 (got 348 columns instead of 2) 
    Line #11 (got 348 columns instead of 2) 
    and so on 

謝謝!

回答

2

嘗試將np.genfromtxt行放入try塊。然後,您可以捕捉到異常並隨心所欲地執行任何操作。

+0

謝謝!它完美的工作! – rudster 2012-04-26 04:43:52