Python3 os.open() Method
Python3 OS File/Directory Methods
Overview
The os.open() method opens a file and sets the required opening options; the mode parameter is optional and defaults to 0777.
Syntax
The **open()** method syntax is as follows:
os.open(file, flags[, mode]);
Parameters
-
file -- The file to open
-
flags -- This parameter can be one of the following options, separated by "|" when there are several:
- os.O_RDONLY: Open read-only
- os.O_WRONLY: Open write-only
- os.O_RDWR : Open for reading and writing
- os.O_NONBLOCK: Do not block when opening
- 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: Acquire a shared lock automatically
- os.O_EXLOCK: Acquire an exclusive lock automatically
- os.O_DIRECT: Eliminate or reduce caching effects
- os.O_FSYNC : Synchronous writes
- os.O_NOFOLLOW: Do not follow symbolic links
-
mode -- Similar to chmod()。
Return Value
Returns the descriptor of the newly opened file.
Example
The following example demonstrates the use of the open() method:
#!/usr/bin/python3
import os, sys
# Open file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Write string
os.write(fd, str.encode("This is test"))
# Close file
os.close( fd )
print ("关闭文件成功!!")
The output of the above program is:
关闭文件成功!!