Python os.open() 方法



Python 方法os.open()打开指定的文件并返回相应的 文件描述符。它还允许我们为文件设置各种标志和模式。始终记住,默认模式为 0o0777(八进制),它将文件权限设置为每个人都可以读取、写入和执行。

语法

以下是 Python os.open() 方法的语法 -

os.open(file, flags, mode, *, dir_fd);

参数

Python os.open() 方法接受以下参数 -

  • file - 要打开的文件名。

  • flags - 以下是 flags 的选项常量。可以使用按位 OR 运算符 (|) 将它们组合在一起。并非所有平台都提供其中的一些选项。

    • 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() 方法类似。

  • dir_fd - 此参数指示一个指向目录的文件描述符。

返回值

Python os.open() 方法返回新打开的文件的文件描述符。

示例

以下示例演示了 open() 方法的使用。在这里,我们通过提供只读访问权限来打开名为“newFile.txt”的文件。

import os, sys

# Open a file
fd = os.open( "newFile.txt", os.O_RDONLY )

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("File contains the following string:", str)

# Close opened file
os.close( fd )
print ("File closed successfully!!")

以上代码将打开一个文件并读取该文件的内容 -

File contains the following string: b'Tutorialspoint'
File closed successfully!!

示例

在以下示例中,我们以读写权限打开一个文件。如果指定的文件不存在,则 open() 方法将创建一个同名文件。

import os, sys

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

# Write one string
os.write(fd, b"This is tutorialspoint")

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("File contains the following string:")
print(str)

# Close opened file
os.close( fd )
print ("File closed successfully!!")

执行以上代码后,将打印以下结果 -

File contains the following string:
b'This is tutorialspoint'
File closed successfully!!
python_files_io.htm
广告
© . All rights reserved.