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

后端 未结 5 1781
温柔的废话
温柔的废话 2021-02-04 02:54

I usually do this in Perl:

whatever.pl

while(<>) {
    #do whatever;
}

then cat foo.txt | whatever.pl

Now, I

相关标签:
5条回答
  • 2021-02-04 03:25

    Try this:

    import fileinput
    for line in fileinput.input():
        process(line)
    
    0 讨论(0)
  • 2021-02-04 03:26

    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.

    0 讨论(0)
  • 2021-02-04 03:31

    Something like this:

    import sys
    
    for line in sys.stdin:
        # whatever
    
    0 讨论(0)
  • 2021-02-04 03:33
    import sys
    def main():
        for line in sys.stdin:
            print line
    if __name__=='__main__':
        sys.exit(main())
    
    0 讨论(0)
  • 2021-02-04 03:42
    import sys
    
    for line in sys.stdin:
        # do stuff w/line
    
    0 讨论(0)
提交回复
热议问题