OS File 中的 os.fdopen(fd[, mode[, b

首页 / Python2入门教程 / OS File 中的 os.fdopen(fd[, mode[, b

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

os.fdopen - 语法

os.fdopen(fd, [, mode[, bufsize]]);
  • fd           -  这是要为其返回文件对象的文件描述符。

  • mode    -  此可选参数是指示如何打开文件的字符串。mode最常用的值是‘r'表示读取,‘w'表示写入(如果文件已经存在,则截断该文件),以及‘a'表示追加。

  • bufsize  -  此可选参数指定文件所需的缓冲区大小:0表示未缓冲,1表示行缓冲,任何其他正值表示使用(大约)该大小的缓冲区。

os.fdopen - 返回值

此方法返回连接到文件描述符的打开文件对象。

无涯教程网

os.fdopen - 示例

以下示例显示了fdopen()方法的用法。

链接:https://www.learnfk.comhttps://www.learnfk.com/python/os-fdopen.html

来源:LearnFk无涯教程网

#!/usr/bin/python

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!!

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入浅出gRPC -〔李林锋〕

MySQL实战45讲 -〔林晓斌〕

深入浅出计算机组成原理 -〔徐文浩〕

零基础学Java -〔臧萌〕

动态规划面试宝典 -〔卢誉声〕

深入浅出分布式技术原理 -〔陈现麟〕

快手 · 移动端音视频开发实战 -〔展晓凯〕

手把手带你写一个MiniSpring -〔郭屹〕

给程序员的写作课 -〔高磊〕

好记忆不如烂笔头。留下您的足迹吧 :)