Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Perl's (<>) in Python? fileinput doesn't work as expected

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.

like image 886
ihightower Avatar asked Dec 29 '10 14:12

ihightower


1 Answers

import sys
import os

for f in sys.argv[1:]:
    if os.path.exists(f):
        for line in open(f).readlines():
            process(line)
like image 174
Brian Clapper Avatar answered Oct 02 '22 20:10

Brian Clapper