更新时间:2023-11-17 23:39:10
简单来说:
import sys
# parse command line
if file_name_given:
inf = open(file_name_given)
else:
inf = sys.stdin
此时您将使用 inf
从文件中读取.根据是否给定文件名,这将从给定的文件或标准输入读取.
At this point you would use inf
to read from the file. Depending on whether a filename was given, this would read from the given file or from stdin.
当你需要关闭文件时,你可以这样做:
When you need to close the file, you can do this:
if inf is not sys.stdin:
inf.close()
然而,在大多数情况下,如果你完成了关闭 sys.stdin
是无害的.
However, in most cases it will be harmless to close sys.stdin
if you're done with it.