Latest web development tutorials

Python3 os.fdopen () method

Python3 OS file / directory methods Python3 OS file / directory methods


Outline

os.fdopen () method is used to create a file object file descriptor fd, and returns the file object.

Unix, is available on Windows.

grammar

fdopen () method syntax is as follows:

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

parameter

  • fd - open file descriptors, under Unix, the descriptor is a small integer.

  • mode - optional, and buffersize parameters, and built-in open function, like Python, mode parameter can specify the "r, w, a, r + , w +, a +, b ", etc., indicates that the file is read-only or read-write can , and open files in binary or text form opens.<Stdio.h> These parameters are similar to the C language and the fopen function specified in the mode parameter.

  • bufsize - Optional Specifies whether the returned file object buffer zone: buffersize = 0, indicates that no buffer zone; bufsize = 1, indicating that the file object is line buffered; bufsize = positive, indicating that the use of a specified size buffer punch the unit is byte, but the size is not exact; bufsize = negative, that the use of a system default buffer size for character devices are generally tty line buffering, and for other files generally are fully buffered.If this parameter is not set, the system default buffer settings.

return value

By file object file descriptor returned.

Examples

The following example demonstrates fdopen () method of use:

#!/usr/bin/python3

import os, sys

# 打开文件
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# 获取以上文件的对象
fo = os.fdopen(fd, "w+")

# 获取当前文章
print ("Current I/O pointer position :%d" % fo.tell())

# 写入字符串
fo.write( "Python is a great language.\nYeah its great!!\n");

# 读取内容
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("Read String is : ", str)

# 获取当前位置
print ("Current I/O pointer position :%d" % fo.tell())

# 关闭文件
os.close( fd )

print ("关闭文件成功!!")

The above program output is:

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
关闭文件成功!!

Python3 OS file / directory methods Python3 OS file / directory methods