ファイル入力/出力

□未翻訳

□翻訳中

□翻訳完了(細田謙二)

■レビュー(Omi Chiba)

ファイル入力/出力

Pythonでは、以下のようにしてファイルを開き、書き込むことができます。

In Python you can open and write in a file with:

1.

2.

>>> file = open('myfile.txt', 'w')

>>> file.write('hello world')

同様に、以下のようにしてファイルを読み出すことができます。

Similarly, you can read back from the file with:

1.

2.

3.

>>> file = open('myfile.txt', 'r')

>>> print file.read()

hello world

代わりに、"rb"を用いてバイナリモードで読むことが可能で、"wb"を用いてバイナリモードで書き込むことが可能です。さらに、追記モード"a"においてファイルを開くこともできます。標準のC言語表記と同じです。

Alternatively, you can read in binary mode with "rb", write in binary mode with "wb", and open the file in append mode "a", using standard C notation.

readコマンドは省略可能な引数であるバイト数を取ります。また、ファイル内の任意の箇所に飛ぶ場合は、seekを利用します。

The read command takes an optional argument, which is the number of bytes. You can also jump to any location in a file using seek.

readを利用して飛んだ場所からファイルを読むことができます。

You can read back from the file with read

1.

2.

3.

>>> print file.seek(6)

>>> print file.read()

world

ファイルを閉じるときは次のようにします。

and you can close the file with:

1.

>>> file.close()

ただし、これは多くの場合必須ではありません。なぜなら、それを参照する変数がスコープ外になったとき、ファイルは自動的に閉じられるからです。

although often this is not necessary, because a file is closed automatically when the variable that refers to it goes out of scope.

web2pyを使用している場合、カレントディレクトリの場所を知る必要はありません。なぜなら、それはweb2pyの設定に依存するからです。request.folder変数は、現在のアプリケーションへのパスを保持しています。パスは、後述するos.path.joinコマンドによって連結することができます。

When using web2py, you do not know where the current directory is, because it depends on how web2py is configured. The variablerequest.folder contains the path to the current application. Paths can be concatenated with the command os.path.join, discussed below.