-1

i am trying to write a command line argument that will take in a File name, that will then try to open the file and read the contents of the file within the Linux command line, if there is no argument passed it will then just open the file that is pre-defind within the Code. currently when i go to run python file.py /home/Desktop/TestFile

i am getting error: unrecognized arguments:

def openfile():
    first = sys.argv
    for arg in sys.argv:
        FILENAME = first
        if len(arg) != 1:
            with open(filename) as f:
        else:
            with open(FILENAME) as f: 
0

I have to say that your code made me scratch my head a little.

Here is how I would do it:

#!/usr/bin/env python3
import sys

def myOpen(aList):
    fileName = "myFile"

    if len(aList) > 1:
        fileName = aList[1]

    try:
        with open(fileName) as f:
            for line in f:
                print(line, end="")
    except IOError:
        print("Can't open file " + fileName + ".")

myOpen(sys.argv)

Now, if I execute this script, I get this result when I do NOT pass an argument, thus using the fileName (myFile) that is in the function:

./args.py
foo
bar
baz

Let's double check the file myFile.

cat myFile 
foo
bar
baz

Here's what happens when I specify a bogus file:

./args.py foo
Can't open file foo.

And finally, when I specify a correct file as an argument:

./args.py vmstat.txt 
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 0  0      0 2419392  76200 642712    0    0    25    10   20   62  0  0 99  1  0

The main issue with your code is this:

FILENAME = first

The first variable contains the entire list that is sys.argv, you cannot open a file with a list element as argument to (open). Check this out:

#!/usr/bin/env python3

import sys

first = sys.argv
FILENAME = first

with open(FILENAME) as f:
    for line in f:
        print(f)

Now when I execute, I get this:

./faultyArgs.py myFile
Traceback (most recent call last):
  File "./faultyArgs.py", line 8, in <module>
    with open(FILENAME) as f:
TypeError: invalid file: ['./faultyArgs.py', 'myFile']

Also, it seems as though you never set the variable filename.

  • Thanks, just a quick question is it possible to have use sys,argv conjunction with agprase ? – David Nov 4 '16 at 20:02
  • It's probably better if you ask that question over at StackOverflow. Best regards. – maulinglawns Nov 5 '16 at 8:34
0
#!/usr/bin/env python
import sys

def openfile(fn):
    file = open(fn, "r")
    out = file.read()
    print out
    file.close()

openfile(sys.argv[1])

Try that, this will work, at least for reading the file out to the terminal

  • This will only work if there is a value in sys.argv[1], otherwise it will fail. – maulinglawns Nov 4 '16 at 17:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.