Python command line 'file input stream'

0 votes
I am a beginner in python coming from C/C++ background. So I was wondering how I would get my 'main.py' to reconize/use the imput given from a bash shell as:

python main.py < text.txt

Any help would be appreciated.
Feb 8 in Python by ana1504.k
• 7,870 points
111 views

1 answer to this question.

0 votes
You can use argparse to create an option parser that accepts a file path and opens it.

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', type='open')
    args = parser.parse_args()

    for line in args.infile:
        print line

if __name__ == '__main__':
    main()
answered Feb 8 by SDeb
• 13,160 points

Related Questions In Python

0 votes
1 answer

How to input optional arguments in python command line?

Please use this code. if len(sys.argv) == 2: first_log ...READ MORE

answered Jul 11 in Python by Suri
15 views
+1 vote
1 answer

Reading a large file, line by line in Python

The correct, fully Pythonic way to read ...READ MORE

answered Aug 21, 2018 in Python by Priyaj
• 56,520 points
53 views
0 votes
1 answer

Enter a 1-10, each on a new line in a file - python

Try something like this: i=1 for i in range(10): ...READ MORE

answered Jun 20 in Python by Greg
16 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 233 views
0 votes
1 answer

In Python, how do I read a file line-by-line into a list?

with open(fname) as f:     content = f.readlines() # you ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 13,160 points
114 views
0 votes
1 answer

How to read a large file, line by line, in Python?

The correct, fully Pythonic way to read ...READ MORE

answered Jul 1 in Python by SDeb
• 13,160 points
26 views