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
.