python文件输入和输出程序_python -o 和-i 输入和输出文件如何理解
你的問(wèn)題可以分為兩部分
1.解析命令行參數(shù)
2.文件讀寫
1.解析命令行參數(shù)
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)
任意順序多個(gè)選項(xiàng)
支持長(zhǎng)短選項(xiàng).
支持默認(rèn)值.
沒有選項(xiàng)時(shí)輸出使用幫助信息.
$ 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打開一個(gè)文件,注意打開模式參數(shù), 用read和write來(lái)進(jìn)行讀寫
#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))
相信你能把合在一塊用起來(lái)
總結(jié)
以上是生活随笔為你收集整理的python文件输入和输出程序_python -o 和-i 输入和输出文件如何理解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 提高抗打击能力_输不起、爱放弃,孩子抗挫
- 下一篇: python3.7安装pip问题_pyt