自动打开在Python中作为命令行参数指定的文件 [英] Automatically open files given as command line arguments in Python
问题描述
我有很多类似于以下内容的Perl脚本.它的作用是它将自动打开作为命令行参数给出的任何文件,在这种情况下,将打印该文件的内容.如果没有给出文件,它将从标准输入中读取.
I have a lot of Perl scripts that looks something like the following. What it does is that it will automatically open any file given as a command line argument and in this case print the content of that file. If no file is given it will instead read from standard input.
while ( <> ) {
print $_;
}
有没有一种方法可以在Python中执行类似的操作而不必显式打开每个文件?
Is there a way to do something similar in Python without having to explicitly open each file?
推荐答案
The fileinput module in Python's standard library is designed exactly for this purpose, and I quote a bit of code from the URL I just gave:
import fileinput
for line in fileinput.input():
process(line)
使用 print
代替 process
,您将获得与Perl代码完全相同的内容.
Use print
in lieu of process
and you have the exact equivalent of your Perl code.
这篇关于自动打开在Python中作为命令行参数指定的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!