Richard Rublev
Richard Rublev

Reputation: 8164

Python: File not exists. Make sure of the right filename

I am using code from one guy

import sys
try:
    filename = sys.argv[1];
    represent_points = int(sys.argv[2]);
    delimeter = sys.argv[3];
    if (delimeter=="space"):
        delimeter = " ";
    if (delimeter=="tab"):
        delimeter = "\t";
    f = open(filename+".txt","r");
except:
    sys.exit("File not exists. Make sure of the right filename");
from string import *
import degree_sampling
degree_sampling.degree_sampling(filename,represent_points,delimeter);

But

milenko@milenko-HP-Compaq-6830s:~/KSCnet_Linux/Python_Code$ python trialrun.py datan 21
File not exists. Make sure of the right filename

That is not true

milenko@milenko-HP-Compaq-6830s:~/KSCnet_Linux/Python_Code$ stat datan.txt
  File: ‘datan.txt’
  Size: 65          Blocks: 8          IO Block: 4096   regular file
Device: 801h/2049d  Inode: 3670784     Links: 1
Access: (0664/-rw-rw-r--)  Uid: ( 1000/ milenko)   Gid: ( 1000/ milenko)
Access: 2016-04-08 10:54:23.695416155 -0300
Modify: 2016-04-08 10:54:23.695416155 -0300
Change: 2016-04-08 10:54:23.695416155 -0300
 Birth: -

What should I do?

Upvotes: 1

Views: 59

Answers (2)

user161778
user161778

Reputation: 534

As a commenter pointed out could be the issue, you're missing the last parameter, the delimeter. Try:

python trialrun.py datan 21 space

Also as another commenter pointed out, to not be confused by this in the future, you should catch only the expected error. Replace this:

except:

With this:

except IOError:

Upvotes: 1

gr1zzly be4r
gr1zzly be4r

Reputation: 2152

python trailrun.py datan 21 has only 2 arguments but the script has:

delimeter = sys.argv[3]

If you check the error I believe that you'll see an IndexError because you're trying to access an index that doesn't exist in sys.argv. You should supply the correct amount of arguments or try to handle cases when a third argument isn't provided to the script.

Also, check out ArgParse. It's the Python provided API for creating command line arguments in scripts.

Upvotes: 2

Related Questions