Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more pythonic way to open a file if given one as an argument or stdin if not?

I'm trying to write a python script which follows the common unix command line pattern of accepting input from stdin if no file name is given. This is what I've been using:

if __name__ == "__main__":
    if len(sys.argv) > 1:
        stream = open(sys.argv[1])
    else:
        stream = sys.stdin

Is there a more pythonic way to do that?

like image 846
Paul Huff Avatar asked Dec 04 '22 14:12

Paul Huff


1 Answers

The fileinput module is perfect for this.

like image 58
Ned Batchelder Avatar answered May 03 '23 07:05

Ned Batchelder