はじめに
Pythonでファイル操作をする方法を毎回調べていたので、備忘録として残します。
目次
ファイル操作
- OPEN:ファイルを開く
- READ:ファイルに記録されているデータを読み取る
- WRITE:ファイルにデータを書き込む
- CLOSE:ファイルを閉じる
txtファイル
読み込んで1行づつ表示
# ファイルを開く(読み取りモードで開く)
f = open("ファイルパス")
# 1行目を読みこんで出力
line = f.readline()
print(line)
# 2行目を読みこんで出力
line = f.readline()
print(line)
for文で表示
# ファイルを開く(読み取りモードで開く)
f = open("ファイルパス")
## すべての行を読み込んで出力
for line in f:
print(line)
書き込みモード
# ファイルを開く(書き込みモードで開く)
f = open("ファイルパスt", mode="w")
# 文字列を書き込んでいく
f.write("Hello")
f.write(" World!\n")
f.write("Goodbye!")
mode="w"
で上書き、mode="a"
で末尾に追記されていく。
クローズ処理
# ファイルを開く(読み取りモードで開く)
f = open("ファイルパス")
print(f.readline())
# ファイルを閉じる
f.close()
with
with 開始処理 as 戻り値:
開始~終了までに行う処理
# ファイルを開く(読み取りモードで開く)
with open("ファイルパス") as f:
print(f.readline())
# closeは不要(自動的にクローズ)
CSVファイル
読み込み
import csv
with open("ファイルパス", newline="", encoding="utf8") as csvfile:
csv_reader = csv.reader(csvfile)
for i in csv_reader:
print(i)
['item', 'price']
['ガム', '128']
['アイス', '108']
['グミ', '148']
['アメ', '32']
リスト形式で出力
import csv
with open("ファイルパス", newline="", encoding="utf8") as csvfile:
csv_reader = csv.reader(csvfile)
data = list(csv_reader)
print(data)
[['item', 'price'], ['ガム', '128'], ['アイス', '108'], ['グミ', '148'], ['アメ', '32']]
書き込み
import csv
header = ["id", "height", "weight"]
physical_measurement = [["A01", 172, 67], ["A02", 165, 57], ["A03", 170, 63]]
with open("ファイルパス", mode="w", newline="", encoding="utf8") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(header)
for row in physical_measurement:
writer.writerow(row)
jsonファイル
読み込み
import json
with open("ファイルパス", newline="", encoding="utf8") as jsonfile:
json_load = json.load(jsonfile)
print(json_load)
[{'item': 'ガム', 'price': 128}, {'item': 'アイス', 'price': 108}, {'item': 'グ
ミ', 'price': 148}, {'item': 'アメ', 'price': 32}]
ダンプ処理
dict型のデータをjsonファイルに書き込む
import json
physical_measurement = {
"id": ["A01", "A02", "A03"],
"height": [172, 165, 170],
"weight": [67, 57, 63]
}
with open("ファイルパス", mode="w", newline="", encoding="utf8") as jsonfile:
json.dump(physical_measurement, jsonfile)