Python3 os.open()方法

open()方法根据标记(flags),并根据设置各种标志在指定模式下打开文件。缺省模式为0777(八进制),当前的 umask 值首先屏蔽。

语法

以下是open()方法的语法:
os.open(file, flags[, mode]);

参数

  • file -- 要打开的文件名

  • flags -- 以下常量是标志 flags 选项。可以用位或操作符相结合。但是其中有些是不是适用于所有平台。

    • os.O_RDONLY: 只读打开
    • os.O_WRONLY: 只写打开
    • os.O_RDWR : 打开读写
    • os.O_NONBLOCK: 不阻塞打开
    • os.O_APPEND: 每个写入附加
    • os.O_CREAT: 如果不存在,创建文件
    • os.O_TRUNC: 截断大小为0
    • os.O_EXCL: 如果创建时文件存在
    • os.O_SHLOCK: 原子获得一个共享锁
    • os.O_EXLOCK: 原子获取排它锁
    • os.O_DIRECT: 消除或减少高速缓存的影响
    • os.O_FSYNC : 同步写入
    • os.O_NOFOLLOW: 不遵循符号链接
  • mode -- 这与  chmod() 方法工作的方式类似

返回值

此方法返回新打开文件的文件描述符。

示例

下面的示例显示open()方法的使用。
#!/usr/bin/python3

import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string

line="this is test" 
# string needs to be converted byte object
b=str.encode(line)
os.write(fd, b)

# Close opened file
os.close( fd)

print ("Closed the file successfully!!")

这将创建给定文件 foo.txt ,然后会将给定的内容写入到文件中,并会产生以下结果:
Closed the file successfully!!

上一篇: Python3文件方法 下一篇: Python3 os文件目录的方法