Python OS file/directory os.open() method
Python OS File/Directory os.open() Method
Description
Method open() Opens the file file, setting various flags according to flags and possibly setting its mode according to mode. The default mode is 0777 (octal), and the current umask value is first masked.
Syntax
The syntax of the open() method is as follows −
os.open(file, flags[, mode]);
Parameters
- file − The name of the file to open.
-
flags − The following constants are flag options. They can be combined using the bitwise OR operator |. Some of these are not available on all platforms.
- os.O_RDONLY: Open for read-only
-
os.O_WRONLY: Open for write-only
-
os.O_RDWR: Open for read and write
-
os.O_NONBLOCK: Open without blocking
-
os.O_APPEND: Append to each write
-
os.O_CREAT: Create the file if it does not exist
-
os.O_TRUNC: Truncate the file to zero
-
os.O_EXCL: Report an error if creating and the file exists
-
os.O_SHLOCK: Atomically acquire a shared lock
-
os.O_EXLOCK: Atomically acquire an exclusive lock
-
os.O_DIRECT: Eliminate or reduce caching effects
-
os.O_FSYNC: Synchronize writes
-
os.O_NOFOLLOW: Do not follow symbolic links
-
mode − This works similarly to the chmod() method.
Return Value
This method returns the file descriptor for the newly opened file.
Example
The following example shows the use of the open() method.
import os, sys
# Open a file
fd = os.open( "foo.txt", os.O_RDWR | os.O_CREAT )
# Write one string
line="this is test"
# string needs to be converted to a byte object
b=str.encode(line)
os.write(fd, b)
# Close the opened file
os.close( fd)
print ("Closed the file successfully!!")
This creates a file named foo.txt and writes the given content to it, producing the following result:
Closed the file successfully!!