[Tutor] python-files

Alan Gauld alan.gauld at yahoo.co.uk
Sun Jan 27 20:01:50 EST 2019


On 27/01/2019 14:57, Asad wrote:

> print("first:", args.first)
> print("second:", args.second)
> 
> When I execute the script it gives error :
> 
> python python_json_20001_oratest_v1.py "file1"
> ('first:', 'file1')
> ('second:', None)

Note that the second file is None.

> Traceback (most recent call last):
>   File "test.py", line 211, in <module>
>     with open(args.second, 'r') as f :
> TypeError: coercing to Unicode: need string or buffer, NoneType found

Note that you get a TypeError because you passed None instead
of a valid filename.

> try :
>         with open(args.second, 'r') as f :
>              for line in f:
>                 print line
> except IOError:
>          print "The default error is err-1 because file2 was not provided "

Note that you are trying to catch an IOError but you are getting a
TypeError. You need to add another except clause for the TypeError.
Or test for a None second file value at the start of your code...

> Does that mean my try and except block is not working because if
> args.second  is None as in this case then it should print "The default
> error is err-1 because file2 was not provided "

It is working. You just aren't catching the correct error type.
It will only type the message you've given if you get an
IOError, but the open() code isn't getting that far,
it's failing on the parameter type.

> Please advice ,

OK, I advise you to delete the text below where you no longer
need it. Some users pay by the byte and all this excess text
costs them money. More than 75% of your message is included
text that we have already seen.

> Thanks,
> 
> 
>> ---------- Forwarded message ----------
>> From: Peter Otten <__peter__ at web.de>
>> To: tutor at python.org
<snip>...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list