1.2.6. Input and Output

念のため、Pythonの入力と出力に関する情報をいくつか挙げておきます。 ファイルの読み書きにはNumPyのメソッドを使用します、 初読時はこの章を飛ばしてもよいです

ファイルとの間で 文字列 を読み書きします(他の型は文字列に変換する必要があります)。 ファイルに書き込むには:

>>> f = open('workfile', 'w') # opens the workfile file
>>> type(f)
<class '_io.TextIOWrapper'>
>>> f.write('This is a test \nand another test')
>>> f.close()

ファイルから読み込むには

In [1]: f = open('workfile', 'r')
In [2]: s = f.read()
In [3]: print(s)
This is a test
and another test
In [4]: f.close()

1.2.6.1. ファイルの反復処理

In [5]: f = open('workfile', 'r')
In [6]: for line in f:
...: print(line)
...:
This is a test
and another test
In [7]: f.close()

ファイルモード

  • 読み取り専用: r

  • 書き込み専用: w

    • Note: Create a new file or overwrite existing file.

  • ファイルを追加します: a

  • 読み書き: r+

  • バイナリーモード: b

    • 注: 特にWindowsでは、バイナリファイルに使用します。