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

旧城冷巷雨未停 提交于 2019-12-02 22:30:32

Try this:

import fileinput
for line in fileinput.input():
    process(line)
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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!