2

I have this little program(I know there is a lot of errors):

#!/usr/bin/python

import os.path
import sys

filearg = sys.argv[0]

if (filearg == ""):
    filearg = input("")

else:

    if (os.path.isfile(filearg)):
        print "File exist"

    else:
        print"No file"
        print filearg
        print "wasn't found"

If i start it by typing python file.py testfile.txt

the output will be always(even if the file doesn't exist):

File exist

If you don't know what iam want from this program, i want to print "File 'filename' wasn't found" if the file isn't exist and if it's exist iam wan't to print "File exist"

Any ideas to solve it? Thanks

1
  • 2
    Too lazy to debug? print filearg... Commented May 27, 2015 at 12:16

2 Answers 2

11

It should be sys.argv[1] not sys.argv[0]:

filearg = sys.argv[1]

From the docs:

The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

Sign up to request clarification or add additional context in comments.

1 Comment

this is correct. sys.argv[0] will always exist because it is the file that is currently being executed (the python script). The first argument always starts at sys.argv[1].
4

The first argument is always the name of the file being executed. This is true for a number of programming languages, you need to use sys.argv[1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.