描述
方法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!!
相關用法
- Python 3 os.fdatasync()用法及代碼示例
- Python 3 os.fstatvfs()用法及代碼示例
- Python 3 os.fchmod()用法及代碼示例
- Python 3 os.fchown()用法及代碼示例
- Python 3 os.fsync()用法及代碼示例
- Python 3 os.fpathconf()用法及代碼示例
- Python 3 os.fchdir()用法及代碼示例
- Python 3 os.fstat()用法及代碼示例
- Python 3 os.ftruncate()用法及代碼示例
- Python 3 os.minor()用法及代碼示例
- Python 3 os.close()用法及代碼示例
- Python 3 os.unlink()用法及代碼示例
- Python 3 os.major()用法及代碼示例
- Python 3 os.rmdir()用法及代碼示例
- Python 3 os.isatty()用法及代碼示例
- Python 3 os.rename()用法及代碼示例
- Python 3 os.walk()用法及代碼示例
- Python 3 os.renames()用法及代碼示例
- Python 3 os.makedirs()用法及代碼示例
- Python 3 os.utime()用法及代碼示例
注:本文由純淨天空篩選整理自 Python 3 - os.fdopen() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。