在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ python -o 和-i 輸入和輸出文件如何理解

python -o 和-i 輸入和輸出文件如何理解

例如我們需要一個(gè)convert.py腳本。它的作用是處理一個(gè)文件,并將處理后的結(jié)果輸出到另一個(gè)文件中。
要求該腳本滿足以下條件:
1.通過-i -o選項(xiàng)來區(qū)別參數(shù)是輸入文件還是輸出文件.

>>> python convert.py -i inputfile -o outputfile

請(qǐng)問這里輸入和輸出文件如何理解?
回答
編輯回答
糖果果

代碼里的每一句input()語句從輸入文件讀取一行文本,
代碼里的每一句print()語句將輸出保存在輸出文件里。

2017年2月6日 13:57
編輯回答
愚念

你的問題可以分為兩部分

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來進(jìn)行讀寫

舉個(gè)小例子,把csv格式轉(zhuǎn)成json

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

相信你能把合在一塊用起來

2017年7月28日 23:26
編輯回答
何蘇葉

現(xiàn)在有一個(gè)數(shù)據(jù)文件,需要你編寫程序讀取這個(gè)文件,并對(duì)其中的數(shù)據(jù)進(jìn)行處理,比如轉(zhuǎn)換、驗(yàn)證、統(tǒng)計(jì)等,然后把處理結(jié)果寫到輸出文件中。

就是這樣。

2017年11月29日 20:50
編輯回答
墨小羽

這里的輸入輸出文件作為命令行參數(shù)一般是文件路徑或者文件名。

2018年1月23日 15:35