Tutorial :How do I iterate over all lines of files passed on the command line?



Question:

I usually do this in Perl:

whatever.pl

while(<>) {      #do whatever;  }  

then cat foo.txt | whatever.pl

Now, I want to do this in Python. I tried sys.stdin but I have no idea how to do as I have done in Perl. How can I read the input?


Solution:1

Try this:

import fileinput  for line in fileinput.input():      process(line)  


Solution:2

import sys  def main():      for line in sys.stdin:          print line  if __name__=='__main__':      sys.exit(main())  


Solution:3

Something like this:

import sys    for line in sys.stdin:      # whatever  


Solution:4

import sys    for line in sys.stdin:      # do stuff w/line  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »