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))
相信你能把合在一塊用起來
總結
以上是生活随笔為你收集整理的python文件输入和输出程序_python -o 和-i 输入和输出文件如何理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 提高抗打击能力_输不起、爱放弃,孩子抗挫
- 下一篇: 比特币可视化工具_比特币再破1.2万大关