简体   繁体   English

Python 相当于 Perl 的 while (<>) {...}?

[英]Python equivalent of Perl's while (<>) {...}?

I write a lot of little scripts that process files on a line-by-line basis.我编写了许多逐行处理文件的小脚本。 In Perl, I use在 Perl 中,我使用

while (<>) {
    do stuff;
}

This is handy because it doesn't care where the input comes from (a file or stdin).这很方便,因为它不关心输入来自哪里(文件或标准输入)。

In Python I use this在 Python 中我使用这个

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

which doesn't seem very elegant.这看起来不是很优雅。 Is there a Python idiom that easily handles file/stdin input?是否有可以轻松处理文件/标准输入的 Python 习语?

The fileinput module in the standard library is just what you want:标准库中的 fileinput 模块正是你想要的:

import fileinput

for line in fileinput.input(): ...
import fileinput
for line in fileinput.input():
    process(line)

This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty.这将遍历 sys.argv[1:] 中列出的所有文件的行,如果列表为空,则默认为 sys.stdin。

fileinput defaults to stdin, so would make it slightly more concise. fileinput默认为 stdin,因此会使其更加简洁。

If you do a lot of command-line stuff, though, this piping hack is very neat.但是,如果您执行大量命令行操作,则此管道 hack非常简洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM