[Tutor] python - files

Alan Gauld alan.gauld at yahoo.co.uk
Sat Jan 26 04:27:01 EST 2019


On 26/01/2019 08:20, Asad wrote:

>    At present I using :
> 
>   if len(sys.argv) == 3:
>     first = sys.argv[1]
>     second = sys.argv[2]
>   else:
>     print "enter the second argument"

> It works well for the following command :
> python test.py file1 file2

Correct because it tests if there are 2 arguments passed

> However I have another case where only file1 may be present so file1 is
> mandatory for this script to run however file2 is optionnal :
> 
>   if len(sys.argv) == 2:
>     first_log = sys.argv[1]
>     second_log = sys.argv[2]

But this will always give an error because you test
for only one argument but then try to read two!
It will always give an error.

> It gives error :
> 
>    second_log = sys.argv[2]
> IndexError: list index out of range
> 
> 
> How do I acheive this because if python test.py file1 file2   then I would
> process both files .

You need to check how many arguments are passed.

if len(sys.argv) == 2:
   # read one argument
elif len(sys.argv) == 3:
  # read 2 arguments
elif ... etc

You could alternatively use exception handling to
catch the IndexError but I think the explicit test
in this case more clearly shows what you are intending.

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