python - Perl 的 (<>) 在 Python 中的等价物是什么? fileinput 没有按预期工作

标签 python perl file-io file command-line-arguments

在 Perl 中使用:

while (<>) {
    # process files given as command line arguments
}

在 Python 中我发现:

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

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

python test.py test1.txt test2.txt filenotexist1.txt filenotexist2.txt test3.txt 作为参数给出。

我尝试了各种使用 try: except: nextfile 的方法,但我似乎无法让它工作。

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

Perl 在这方面做得很好。我已经在网上搜索过这个问题,但在任何地方都找不到这个问题的答案。

最佳答案

import sys
import os

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

关于python - Perl 的 (<>) 在 Python 中的等价物是什么? fileinput 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4554819/

相关文章:

java - Python 在 Android 上的局限性是什么?

python - 将传递分配给 Python 中的函数

perl - 使用 R 包 gdata 时的路径规范

Perl在旧的Perl上没有警告 'experimental'

python - 如何使用 python io 库写入外部文件

c++ - 将文件内容的字符对读入数组

python - 在 Python 中实现完整的 RSA

python - 如何随时间执行python字符串?

perl - 当 WxPerl 类没有方法时怎么办?

ios - 如何在 iOS 中读取、写入和检查不区分大小写的文件名?