Python3 os.open() Method
Python3 OS File/Directory Methods
Overview
The os.open()
method is used to open a file and set the necessary open options. The mode parameter is optional and defaults to 0777.
Syntax
open() method syntax is as follows:
os.open(file, flags[, mode]);
Parameters
-
file -- The file to be opened.
-
flags -- This parameter can be a combination of the following options, separated by "|":
-os.O_RDONLY: Open for reading only.
-os.O_WRONLY: Open for writing only.
-os.O_RDWR: Open for reading and writing.
-os.O_NONBLOCK: Open in non-blocking mode.
-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 (must have write permission).
-os.O_EXCL: Return an error if the specified file exists.
-os.O_SHLOCK: Automatically obtain a shared lock.
-os.O_EXLOCK: Automatically obtain an exclusive lock.
-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 a file
fd = os.open("foo.txt", os.O_RDWR|os.O_CREAT)
# Write a string
os.write(fd, str.encode("This is test"))
# Close the file
os.close(fd)
print("Closed the file successfully!!")
Executing the above program outputs:
Closed the file successfully!!