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非常好.我在网上搜索过这个,但我无法在任何地方找到答案.
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)