python文件输入和输出程序_python -o 和-i 输入和输出文件如何理解

你的问题可以分为两部分

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))

相信你能把合在一块用起来

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值