gpt4 book ai didi

Python 等价于 Perl 的 while (<>) {...}?

转载 作者:IT老高 更新时间:2023-10-28 20:29:48 26 4
gpt4 key购买 nike

我编写了很多逐行处理文件的小脚本。在 Perl 中,我使用

while (<>) {
do stuff;
}

这很方便,因为它不关心输入来自哪里(文件或标准输入)。

在 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

这似乎不是很优雅。是否有 Python 习语可以轻松处理文件/stdin 输入?

最佳答案

标准库中的fileinput模块正是你想要的:

import fileinput

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

关于Python 等价于 Perl 的 while (<>) {...}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/807173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com