0

好的,我有这个简化的代码来绘制一个简单的等高线图:

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

谢谢!

4

1 回答 1

2

尝试将np.genfromtxt行放在 try 块内。然后,您可以捕获异常并使用它做任何您喜欢的事情。

于 2012-04-26T04:25:12.807 回答