[英]How to split input arguments in Python
我有下面的代码,它需要 1 个或多个文件名作为参数。
它适用于一个文件,但现在输入参数可以是多个文件,例如1.json 2.json 3.json
。
我该如何处理?
import sys
import os
import json
inFile = sys.argv[1]
print(inFile)
with open(inFile, 'r') as file:
try:
json_data = json.load(file)
except ValueError as e:
print "Invalid Json supplied:%s" % e
exit(1)
else:
print "json file ok"
print(json_data)
由于argv
是一个列表(解析传递的 arg 字符串已为您完成),您可以遍历它,跳过argv[0]
这是程序文件名:
import json
import sys
for arg in sys.argv[1:]:
with open(arg, "r") as file:
try:
json_data = json.load(file)
print "json file ok"
print json_data
except ValueError as e:
print "Invalid JSON supplied: %s" % e
exit(1)
您可能希望将此数据放入列表中,以便您可以在程序中使用它:
import json
import sys
data = []
for arg in sys.argv[1:]:
with open(arg, "r") as file:
try:
data.append(json.load(file))
except ValueError as e:
print "Invalid JSON supplied: %s" % e
exit(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.