something like this:
#!/usr/bin/python3
import sys
def myFirstFunction():
return open(sys.argv[1], 'r')
openFile = myFirstFunction()
for line in openFile:
print (line.strip()) #remove '\n'? if not remove .strip()
#do other stuff
openFile.close() #don't forget to close open file
then I would call it like the following:
./readFile.py temp.txt
which would output the contents of temp.txt
sys.argv[0]
outputs the name of script. In this case ./readFile.py
Updating My Answer
because it seems others want a try
approach
How do I check whether a file exists using Python?
is a good question on this subject of how to check if a file exists. There appears to be a disagreement on which method to use, but using the accepted version it would be as followed:
#!/usr/bin/python3
import sys
def myFirstFunction():
try:
inputFile = open(sys.argv[1], 'r')
return inputFile
except Exception as e:
print('Oh No! => %s' %e)
sys.exit(2) #Unix programs generally use 2 for
#command line syntax errors
# and 1 for all other kind of errors.
openFile = myFirstFunction()
for line in openFile:
print (line.strip())
#do other stuff
openFile.close()
which would output the following:
$ ./readFile.py badFile
Oh No! => [Errno 2] No such file or directory: 'badFile'
you could probably do this with an if
statement, but I like this comment on EAFP VS LBYL