且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从文件或标准输入读取

更新时间:2023-11-18 07:51:57

在最简单的术语:

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