I have a function that processes file contents, but right now I have the filename hardcoded in the function like this as a keyword argument:
def myFirstFunc(filename=open('myNotes.txt', 'r')):
pass
and I call it like this:
myFirstFunc()
I would like to treat the argument as a filename and process the contents.
How do I modify the statement above? I tried this:
filename=sys.argv[1] # or is it 0?
How do I call it?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With