Python 相当于 Perl 的 while (<>) {...}? [英] Python equivalent of Perl's while (<>) {...}?
本文介绍了Python 相当于 Perl 的 while (<>) {...}?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了许多逐行处理文件的小脚本.在 Perl 中,我使用
I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use
while (<>) {
do stuff;
}
这很方便,因为它不关心输入来自哪里(文件或标准输入).
This is handy because it doesn't care where the input comes from (a file or stdin).
在 Python 中我使用这个
In Python I use this
if len(sys.argv) == 2: # there's a command line argument
sys.stdin = file(sys.argv[1])
for line in sys.stdin.readlines():
do stuff
这看起来不是很优雅.是否有可以轻松处理文件/标准输入输入的 Python 习惯用法?
which doesn't seem very elegant. Is there a Python idiom that easily handles file/stdin input?
推荐答案
标准库中的fileinput模块正是你想要的:
The fileinput module in the standard library is just what you want:
import fileinput
for line in fileinput.input(): ...
这篇关于Python 相当于 Perl 的 while (<>) {...}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文