Input from a file as a command line argument

John Machin sjmachin at
Sat Apr 5 23:26:37 CEST 2003

Teemu Luojola <teemu.luojola at> wrote in message news:<3E8EDBDA.7020701 at>...
> If I make an executable script in linux environment, how can I pass 
> input to that script from a file on command line? Like the following:
> $ input.txt

import sys
file_name = sys.argv[1]
file_handle = file(file_name)
for line in file_handle:
   print line

> or perhaps
> $ < input.txt

import sys
for line in sys.stdin:
   print line

Notes: (1) This will work with Windows too. (2) The above is written
for Python version 2.2 (the latest production release) -- if you have
only an earlier version, (like 1.5.2), you may like to read back
through the "What's new in Python x.y" series on to see
what you are missing. (3) Unless you are forced to by inability to
upgrade your Python version, or a need to read another's code, you
don't need to know about xreadlines() -- the "for line in file_object"
paradigm is the thoroughly modern way.


More information about the Python-list mailing list