简体   繁体   中英

What is the most Pythonic way of handling standard input?

I've started doing programming contests/challenges, and often the questions involve reading in from standard input. I've been doing

import fileinput

inputLines = []

for line in fileinput.input():
    inputLines.append(line)

I then can do whatever calculations I need to do with inputLines . Is there a more Pythonic (ie, better) way of doing this?

If you just want to read from stdin , not from any files named in the command line, then you should not use fileinput .

If you want a list containing the lines from stdin , then:

import sys
inputLines = list(sys.stdin)
import sys
for line in sys.stdin:
    print "The line was", line

I think fileinput is the flexible way to do it in Python, given they made a module just to do that.

If you know more about what type of input you will be reading, there might be libraries that are better suited to your needs. For example, I do a lot of numerical work, so pandas works great for me because it has a read_csv . Take a look at the docs (and try and tell us more about specific reading needs, if you can narrow it down).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM