この文書の現在のバージョンと選択したバージョンの差分を表示します。
| 両方とも前のリビジョン 前のリビジョン 次のリビジョン | 前のリビジョン | ||
|
プログラミング:python:基本:ファイル処理 [2020/07/05 15:18] sotoyama |
プログラミング:python:基本:ファイル処理 [2020/07/05 22:45] (現在) sotoyama [CSVの読み書き] |
||
|---|---|---|---|
| ライン 29: | ライン 29: | ||
| | t | テキストファイル。r,w,x,a,+と組み合わせて指定。 | | | t | テキストファイル。r,w,x,a,+と組み合わせて指定。 | | ||
| | b | バイナリファイル。r,w,x,a,+と組み合わせて指定。 | | | b | バイナリファイル。r,w,x,a,+と組み合わせて指定。 | | ||
| + | |||
| + | === encodingオプション === | ||
| + | |||
| + | PythonはUTF-8をデフォルトとする。UTF-8以外の文字コードを読み込む場合はeoncodingオプションを指定する。 | ||
| + | |||
| + | ^ 値 ^ 別名 ^ 説明 ^ | ||
| + | | shift_jis | shiftjisi, sjis | シフトJIS | | ||
| + | | cp932 | 932, ms932, mskanji, ms-kanji | Windows用のシフトJIS | | ||
| + | | euc-jp | eucjp, ujis, u-jis | EUC-JP | | ||
| + | | iso2022_jp | iso2022jp, iso-2022-jp | JIS | | ||
| + | |||
| + | <code python> | ||
| + | with open("test.txt", encoding='shift-jis') as f: | ||
| + | l = f.readlines() | ||
| + | </code> | ||
| + | |||
| + | === newlineオプション === | ||
| + | |||
| + | newlineオプションにより、改行コードを指定することができる。 | ||
| + | |||
| + | ^ 値 ^ 説明 ^ | ||
| + | | \r | CR | | ||
| + | | \n | LF | | ||
| + | | \r\n | CRLF | | ||
| + | |||
| + | <code python> | ||
| + | with open("test.txt", encoding='shift-jis', newline='\r\n') as f: | ||
| + | l = f.readlines() | ||
| + | </code> | ||
| ライン 44: | ライン 73: | ||
| | write(データ) | データを書き込む。 | | | write(データ) | データを書き込む。 | | ||
| | writelines(リスト) | リストで構成されたデータを書き込む。 | | | writelines(リスト) | リストで構成されたデータを書き込む。 | | ||
| + | |||
| + | === 読み込み === | ||
| + | |||
| + | <code python> | ||
| + | # 1行毎にリストにして読み込み | ||
| + | with open("test.txt") as f: | ||
| + | l = f.readlines() | ||
| + | |||
| + | print(l) | ||
| + | |||
| + | # 1行ずつ読み込み | ||
| + | with open("test.txt") as f: | ||
| + | while True: | ||
| + | l = f.readline() | ||
| + | print(l) | ||
| + | if not l: | ||
| + | break | ||
| + | </code> | ||
| + | |||
| + | |||
| + | === 書き込み === | ||
| + | |||
| + | <code python> | ||
| + | #書き込み | ||
| + | with open("test.txt", "w") as f: | ||
| + | f.write("abc\n") | ||
| + | </code> | ||
| + | |||
| + | ==== CSVの読み書き ==== | ||
| + | |||
| + | === 読み込み === | ||
| + | |||
| + | <code python> | ||
| + | import csv | ||
| + | |||
| + | with open("test.csv") as f: | ||
| + | reader = csv.reader(f) | ||
| + | for l in reader: | ||
| + | print(l) | ||
| + | </code> | ||
| + | |||
| + | |||
| + | === 書き込み === | ||
| + | |||
| + | <code python> | ||
| + | import csv | ||
| + | |||
| + | datas = [ [1, 2, 3], [4, 5, 6] ] | ||
| + | |||
| + | # 全量書き込み | ||
| + | with open("test1.csv", "w") as f: | ||
| + | writer = csv.writer(f) | ||
| + | writer.writerows(datas) | ||
| + | |||
| + | # 1行書き込み | ||
| + | with open("test2.csv", "w") as f: | ||
| + | writer = csv.writer(f) | ||
| + | for data in datas: | ||
| + | writer.writerow(data) | ||
| + | </code> | ||