In Perl one uses:
while (<>) {
# process files given as command line arguments
}
In Python I found:
import fileinput
for line in fileinput.input():
process(line)
But, what happens when the file given in the command line does NOT exist?
python test.py test1.txt test2.txt filenotexist1.txt filenotexist2.txt test3.txt
was given as the argument.
I tried various ways of using try: except: nextfile
, but I couldn't seem to make it work.
For the above commandline, the script should run for test1-3.txt
but just go to next file silent when the file is NOT found.
Perl does this very well. I have searched this all over the net, but I couldn't find the answer to this one anywhere.
import sys
import os
for f in sys.argv[1:]:
if os.path.exists(f):
for line in open(f).readlines():
process(line)
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