Python3-os-fdopen

提供:Dev Guides
移動先:案内検索

Python 3-os.fdopen()メソッド

説明

メソッド* fdopen()は、ファイル記述子 *fd に接続された開いているファイルオブジェクトを返します。 その後、ファイルオブジェクトで定義されたすべての機能を実行できます。

構文

以下は* fdopen()*メソッドの構文です-

os.fdopen(fd, [, mode[, bufsize]]);

パラメーター

  • fd -これは、ファイルオブジェクトが返されるファイル記述子です。
  • mode -このオプションの引数は、ファイルを開く方法を示す文字列です。 modeの最も一般的に使用される値は、読み取り用の 'r'、書き込み用の 'w'(既に存在する場合はファイルを切り捨てる)、および追加用の 'a’です。
  • bufsize -このオプションの引数は、ファイルの目的のバッファサイズを指定します。0はバッファなし、1は行バッファ、他の正の値は(ほぼ)そのサイズのバッファを使用することを意味します。

戻り値

このメソッドは、ファイル記述子に接続された開いているファイルオブジェクトを返します。

次の例は、fdopen()メソッドの使用法を示しています。

#!/usr/bin/python3
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Now get a file object for the above file.
fo = os.fdopen(fd, "w+")

# Tell the current position
print ("Current I/O pointer position :%d" % fo.tell())

# Write one string
fo.write( "Python is a great language.\nYeah its great!!\n");

# Now read this file from the beginning.
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("Read String is : ", str)

# Tell the current position
print ("Current I/O pointer position :%d" % fo.tell())

# Close opened file
fo.close()

print ("Closed the file successfully!!")

結果

上記のプログラムを実行すると、次の結果が生成されます-

Current I/O pointer position :0
Read String is :  This is testPython is a great language.
Yeah its great!!

Current I/O pointer position :45
Closed the file successfully!!