Automatically open files given as command line arguments in Python

自古美人都是妖i 提交于 2021-02-11 10:54:10

问题


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 $_;
}

Is there a way to do something similar in Python without having to explicitly open each file?


回答1:


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)

Use print in lieu of process and you have the exact equivalent of your Perl code.



来源:https://stackoverflow.com/questions/2533673/automatically-open-files-given-as-command-line-arguments-in-python

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