Python3 os.open() Method
Python3 OS File/Directory Methods
Overview
The os.open() method is used to open a file and set the required opening options. The mode parameter is optional, defaulting to 0777.
Syntax
open()The method syntax is as follows:
os.open(file, flags[, mode]);
Parameters
file-- The file to open
flags-- This parameter can be the following options, separated by "|":
- os.O_RDONLY:Open in read-only mode
- os.O_WRONLY:Open in write-only mode
- os.O_RDWR :Open in read-write mode
- os.O_NONBLOCK:Open without blocking
- os.O_APPEND:Open in append mode
- os.O_CREAT:Create and open a new file
- os.O_TRUNC:Open a file and truncate its length to zero (write permission required)
- os.O_EXCL:Return an error if the specified file exists
- os.O_SHLOCK:Automatically acquire a shared lock
- os.O_EXLOCK:Automatically acquire an exclusive lock
- os.O_DIRECT:Eliminate or reduce cache effects
- os.O_FSYNC :Synchronous write
- os.O_NOFOLLOW:Do not follow soft links
mode-- Similarchmod()。
Return Value
Returns the file descriptor of the newly opened file.
Example
The following example demonstrates the use of the open() method:
#!/usr/bin/python3
import os, sys
# 打开文件
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# 写入字符串
os.write(fd, str.encode("This is test"))
# 关闭文件
os.close( fd )
print ("关闭文件成功!!")
The output of the above program is:
File closed successfully!!Other Extensions