在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做得非常好。我在网上搜索了很多,但无法找到答案。