http://docs.python.jp/3/tutorial/inputoutput.html
repr
はインタプリタ用の文字列表現= "Hello!\n"
s print(s)
print(repr(s))
Hello!
'Hello!\n'
str.format
for k in range(0, 10):
print("{0:3d} {1:3d} {2:3d}".format(k, 2 * k, 2 * k + 1))
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
5 10 11
6 12 13
7 14 15
8 16 17
9 18 19
str.format
はキーワード引数も使えるfor k in range(0, 10):
print("Index = {index}, Even = {even}, Odd = {odd}".format(index = k, even = 2 * k, odd = 2 * k + 1))
Index = 0, Even = 0, Odd = 1
Index = 1, Even = 2, Odd = 3
Index = 2, Even = 4, Odd = 5
Index = 3, Even = 6, Odd = 7
Index = 4, Even = 8, Odd = 9
Index = 5, Even = 10, Odd = 11
Index = 6, Even = 12, Odd = 13
Index = 7, Even = 14, Odd = 15
Index = 8, Even = 16, Odd = 17
Index = 9, Even = 18, Odd = 19
open
with open('datafile.txt', 'w') as f:
"Hello, world!\n")
f.write("Hello, world!\n")
f.write("Hello, world!\n")
f.write(
with open('datafile.txt', 'r') as f:
for line in f:
print(line, end='')
Hello, world!
Hello, world!
Hello, world!
readlines
with open('datafile.txt', 'w') as f:
"11111\n")
f.write("22222\n")
f.write("33333\n")
f.write(
with open('datafile.txt', 'r') as f:
= f.readlines()
lines for line in reversed(lines):
print(line, end='')
33333
22222
11111
json
import json
= [ 111, 222, 333, { 'x': 123, 'y': 456 } ]
obj
with open('datafile.json', 'w') as f:
= json.dumps(obj)
s
f.write(s)
with open('datafile.json', 'r') as f:
= json.load(f)
seq for o in seq:
print(o)
111
222
333
{'y': 456, 'x': 123}
json.dump
とjson.load
import json
= [ 111, 222, 333, { 'x': 123, 'y': 456 } ]
obj
with open('datafile.json', 'w') as f:
json.dump(obj, f)
with open('datafile.json', 'r') as f:
= json.load(f)
seq for o in seq:
print(o)
111
222
333
{'x': 123, 'y': 456}