日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

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

發(fā)布時(shí)間:2025/3/20 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python文件输入和输出程序_python -o 和-i 输入和输出文件如何理解 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

你的問(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)題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。