Richard Rublev Richard Rublev - 2 months ago 6
Python Question

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?

Answer

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.

Comments