file = open("input.txt", encoding="utf-8") #ファイルを開く
s = file.read() #ファイルを読み込む
file.close() #ファイルを閉じる
print(s) #読み込んだ内容を表示する
file = open("output.txt", mode="w", encoding="utf-8") #ファイルを開く
file.write("Hello World") #ファイルに書き込む
file.close() #ファイルを閉じる
file = open("output.txt", mode="w", encoding="utf-8") #ファイルを開く
try: #ファイルを処理する際は例外を考慮し、確実にファイルを閉じる
file.write("Hello World") #ファイルに書き込む
finally:
file.close() #ファイルを閉じる
#with を使うと自動で閉じる
with open("output.txt", mode="w", encoding="utf-8") as f:
f.write("Hello World")
with open("input.txt", encoding="utf-8") as tf:
for line in tf: #テキストファイルを 1 行ずつ処理する
print(line)
import json
#辞書型データ
data = {
"no" : 5,
"code" : ("jas", 1, 19),
"scr" : "be quick to listen, slow to speak. slow to anger"
}
#json として出力
filename = "output.json"
with open(filename, "w") as fp:
json.dump(data, fp)
#json として入力
with open(filename, "r") as fp:
r = json.load(fp)
print("no=", r["no"])
print("code=", r["code"])
print("scr=", r["scr"])