Python os.open() Method
os.open() Overview
The os.open() method is used to open a file and set the desired open options. The mode parameter is optional and defaults to 0777.
os.open() Syntax
The syntax format of the open() method is as follows.
os.open(file, flags[, mode]);
os.open() Parameters
- file – Files to open
- flags – This parameter can be the following options, with multiple separated by
|
.- os.O_RDONLY: Open as read-only
- os.O_WRONLY: Open as write-only
- os.O_RDWR : Open as read/write
- os.O_NONBLOCK: No blockage when opened
- os.O_APPEND: Open as append
- os.O_CREAT: Create and open a new file
- os.O_TRUNC: Open a file and truncate it to zero length (must have write access)
- os.O_EXCL: If the specified file exists, return an error
- os.O_SHLOCK: Automatic acquisition of shared locks
- os.O_EXLOCK: Automatic acquisition of independent locks
- os.O_DIRECT: Eliminate or reduce caching effects
- os.O_FSYNC : Synchronous writing
- os.O_NOFOLLOW: Do not track soft links
- mode – Similar with chmod()。
os.open() Return Value
Returns the descriptor of the newly opened file.
os.open() Demo
The following example demonstrates the use of the open() method.
#!/usr/bin/python3
import os, sys
# open file
fd = os.open( "/root/apidemos.com.txt", os.O_RDWR|os.O_CREAT )
# write string
os.write(fd, str.encode("This is test for apidemos.com"))
# close file
os.close( fd )
print ("Close file successfully!!!")
Output: