你的问题可以分为两部分
1.解析命令行参数
2.文件读写
1.解析命令行参数
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-o", "--output", dest="out_filename",
help="write to output OUT_FILE", metavar="OUT_FILE")
parser.add_option("-i", "--input", dest="in_filename",
help="read from input IN_FILE", metavar="OUT_FILE")
(options, args) = parser.parse_args()
print(options)
任意顺序多个选项
支持长短选项.
支持默认值.
没有选项时输出使用帮助信息.
$ python3 opt_test.py --help
Usage: opt_test.py [options]
Options:
-h, --help show this help message and exit
-o OUT_FILE, --output=OUT_FILE
write to output OUT_FILE
-i OUT_FILE, --input=OUT_FILE
read from input IN_FILE
$ python3 opt_test.py -i somedata.txt -o result.txt
{'out_filename': 'result.txt', 'in_filename': 'somedata.txt'}
2.文件读写
用open打开一个文件,注意打开模式参数, 用read和write来进行读写
#Read CSV File
def read_csv(file, json_file, format):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([{title[i]:row[title[i]] for i in range(len(title))}])
write_json(csv_rows, json_file, format)
#Convert csv data into json and write it
def write_json(data, json_file, format):
with open(json_file, "w") as f:
if format == "pretty":
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '),encoding="utf-8",ensure_ascii=False))
else:
f.write(json.dumps(data))
相信你能把合在一块用起来