在 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/