日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/3/20 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 输入和输出文件如何理解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。