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
Try this:
import fileinput
for line in fileinput.input():
process(line)
OTHER TIPS
import sys
def main():
for line in sys.stdin:
print line
if __name__=='__main__':
sys.exit(main())
Something like this:
import sys
for line in sys.stdin:
# whatever
import sys
for line in sys.stdin:
# do stuff w/line
I hate to beat a dead horse, but may I suggest using a pure function?
import sys
def main(stdin):
for line in stdin:
print("You said: " + line.strip())
if __name__ == "__main__":
main(sys.stdin)
This approach is nice because main is dependent purely on its input and you can unit test it with anything that obeys the line-delimited input stream paradigm.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow