2016-03-26   python 

Python写経(入出力)

参照

http://docs.python.jp/3/tutorial/inputoutput.html

reprはインタプリタ用の文字列表現

s = "Hello!\n"
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:
    f.write("Hello, world!\n")
    f.write("Hello, world!\n")
    f.write("Hello, world!\n")

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:
    f.write("11111\n")
    f.write("22222\n")
    f.write("33333\n")

with open('datafile.txt', 'r') as f:
    lines = f.readlines()
    for line in reversed(lines):
        print(line, end='')
33333
22222
11111

標準モジュールjson

import json

obj = [ 111, 222, 333, { 'x': 123, 'y': 456 } ]

with open('datafile.json', 'w') as f:
    s = json.dumps(obj)
    f.write(s)

with open('datafile.json', 'r') as f:
    seq = json.load(f)
    for o in seq:
        print(o)
111
222
333
{'y': 456, 'x': 123}

json.dumpjson.load

import json

obj = [ 111, 222, 333, { 'x': 123, 'y': 456 } ]

with open('datafile.json', 'w') as f:
    json.dump(obj, f)

with open('datafile.json', 'r') as f:
    seq = json.load(f)
    for o in seq:
        print(o)
111
222
333
{'x': 123, 'y': 456}
 2016-03-26   python