【8-1】
▲テキスト・モードの場合
-------------------
>>> path = 'test.txt'
>>> f = open(path)
>>> s = f.read()
>>> f.close()
>>> print(type(s))
<class 'str'>
>>> print(s)
line 1
line 2
line 3
line 4
line 5
-------------------


▲バイナリ・モードの場合
-------------------
>>> path = 'test.dat'
>>> f = open(path)
>>> f = open(path, mode='rb')
>>> s = f.read()
>>> f.close()
>>> print(type(s))
<class 'bytes'>
>>> print(s)
b'\xff\xff\xff\xff'
-------------------


【8-2】
▲テキスト・モード＋read()
-------------------
>>> path = 'test.txt'
>>> f = open(path)
>>> s = f.read()
>>> f.close()
>>> print(s)
line 1
line 2
line 3
line 4
line 5
-------------------


▲テキスト・モード＋readlines()
-------------------
>>> path = 'test.txt'
>>> f = open(path)
>>> l = f.readlines()
>>> f.close()
>>> print(l)
['line 1\n', 'line 2\n', 'line 3\n', 'line 4\n', 'line 5\n']
>>> print(l[1])
line 2
-------------------


▲テキスト・モード＋readline()
-------------------
>>> path = 'test.txt'
>>> f = open(path)
>>> single_line = f.readline()
>>> print(single_line)
line 1
>>> f.close()
-------------------


▲バイナリ・モード＋read()
-------------------
>>> path = 'test.dat'
>>> f = open(path, mode='br')
>>> print(f.read())
b'\xff\xff\xff\xff'
>>> f.close()
-------------------


【8-3】
▲文字列の書き込み
-------------------
>>> path = 'test.txt'
>>> f = open(path, mode='w')
>>> f.write('New line')
8
>>> f.close()

>>> f = open(path)
>>> print(f.read())
New line
>>> f.close()
-------------------


▲リストの書き込み
-------------------
>>> path = 'test.txt'
>>> l = ['New line 1\n', 'New line 2\n', 'New line 3\n']
>>> f = open(path, mode='a')
>>> f.writelines(l)
>>> f.close()

>>> f = open(path)
>>> print(f.read())
New line
New line 1
New line 2
New line 3
>>> f.close()
-------------------


▲バイナリ・ファイルの上書き
-------------------
>>> path = 'test.dat'
>>> f = open(path, mode='wb')
>>> f.write(b'\x00\x00\x00\x00')
4
>>> f.close()

>>> f = open(path, mode='br')
>>> print(f.read())
b'\x00\x00\x00\x00'
>>> f.close()
-------------------