首页 > Python资料 博客日记

Python os.fdopen()方法

2023-08-06 15:41:46Python资料围观241

文章Python os.fdopen()方法分享给大家,欢迎收藏Python资料网,专注分享技术知识

Python的os.fdatasync()方法返回连接到文件描述符fd的打开的文件对象。 然后可以对文件对象执行所有定义的函数功能。

语法

以下是fdopen()方法的语法 -

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

参数

  • fd − 这是要返回文件对象的文件描述符。
  • 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!!

版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐