Python3 os.fdopen() Method
Python3 OS File/Directory Methods
Overview
The os.fdopen() method creates a file object from a file descriptor fd and returns that file object.
This method is an alias of the built-in function open() and accepts the same arguments; the only difference is that the first argument of fdopen() must be an integer.
Syntax
The **fdopen()** method syntax is as follows:
os.fdopen(fd, [, mode[, bufsize]]);
Parameters
-
fd -- The descriptor of the opened file; on Unix a descriptor is a small integer.
-
mode -- Optional. As with Python's built-in open function, the mode parameter can specify 'r,w,a,r+,w+,a+,b' and so on, indicating whether the file is read-only or readable and writable, and whether it is opened in binary or text form. These parameters are similar to those of the
fopen function's mode parameter in C. -
bufsize -- Optional, specifies whether the returned file object is buffered: bufsize=0 means unbuffered; bufsize=1 means line buffered; a positive bufsize means a buffer of that size in bytes, though the size is not exact; a negative bufsize means a system-default sized buffer, usually line buffered for tty character devices and fully buffered for other files. If this parameter is not specified, the system default buffering is used.
Return Value
The file object returned through the file descriptor.
Example
The following example demonstrates the use of the fdopen() method:
Example (Python 3.0+)
#!/usr/bin/python3
import
os
,
sys
Opening a File
fd
=
os
.
open
(
"
foo.txt
"
,
os
.
O_RDWR
|
os
.
O_CREAT
)
Get the object of the above file
fo
=
os
.
fdopen
(
fd
,
"
w+
"
)
Get the current position
(
"
Current I/O pointer position :%d
"
%
fo
.
tell
(
)
)
Write a string
fo
.
write
(
"
Python is a great language.
\n
Yeah its great!!
\n
"
)
;
Read the content
os
.
lseek
(
fd
,
0
,
0
)
str
=
os
.
read
(
fd
,
100
)
(
"
Read String is :
"
,
str
)
Get the current position
(
"
Current I/O pointer position :%d
"
%
fo
.
tell
(
)
)
Closing a File
os
.
close
(
fd
)
(
"
File closed successfully!!
"
)
The output of the above program 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
关闭文件成功!!