Python中Perl(<>)的等价物是什么?fileinput无法按预期工作

ihi*_*wer 7 python perl file-io file command-line-arguments

在Perl中使用:

while (<>) {
    # process files given as command line arguments
}
Run Code Online (Sandbox Code Playgroud)

在Python中我发现:

import fileinput
for line in fileinput.input():
    process(line)
Run Code Online (Sandbox Code Playgroud)

但是,当命令行中给出的文件不存在时会发生什么?

python test.py test1.txt test2.txt filenotexist1.txt filenotexist2.txt test3.txt 被作为论据.

我尝试了各种使用方法try: except: nextfile,但我似乎无法使其工作.

对于上面的命令行,脚本应该运行test1-3.txt但只是在找不到文件时转到下一个文件静默.

Perl非常好.我在网上搜索过这个,但我无法在任何地方找到答案.

Bri*_*per 5

import sys
import os

for f in sys.argv[1:]:
    if os.path.exists(f):
        for line in open(f).readlines():
            process(line)
Run Code Online (Sandbox Code Playgroud)

  • @ihightower是的.拿我的方法,把它放入一个模块并导入它.你需要的只是`for read_lines()中的行:`.尽管如此,Python不会以最少的击键次数来瞄准模糊操作符,所以你不会像Perl的`<>`那样找到简洁的东西,但你可以*将方法重命名为`rl()`以获得`for l in rl():`如果你绝对必须的话. (2认同)
  • 这不能考虑其他可能的错误,例如文件不可读,文件是目录,文本文件被锁定等。我完全同意OP的观点,即如果`fileinput`要有用,它应该提供对这方面的控制它的操作。 (2认同)