rudster
rudster

Reputation: 1377

Python and MatPlotlib: ValueError and skip_header

Okay, I have this simplified code to plot a simple contour map:

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()

Let's say skip_header is supposed to be 5. I want to know what should I do to avoid the program from crashing at the end, if the user inputs a value other than 5.

This is the error that I got:

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

Thank you!

Upvotes: 0

Views: 348

Answers (1)

happydave
happydave

Reputation: 7187

Try putting the np.genfromtxt line inside the try block. You can then catch the exception and do whatever you like with it.

Upvotes: 2

Related Questions