Python os.open() Method



Python method os.open() opens the specified file and returns a corresponding file descriptor. It also allows us to set various flags and modes to files. Always remember the default mode is 0o0777 (octal), which set the file permissions to read, write, and execute by everyone.

Syntax

Following is the syntax for Python os.open() method −

os.open(file, flags, mode, *, dir_fd);

Parameters

The Python os.open() method accepts the following parameters −

  • file − File name to be opened.

  • flags − The following constants are options for the flags. They can be combined using the bitwise OR operator (|). Some of them are not available on all platforms.

    • 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 − do not block on open

    • os.O_APPEND − append on each write

    • os.O_CREAT − create file if it does not exist

    • os.O_TRUNC − truncate size to 0

    • os.O_EXCL − error if create and file exists

    • os.O_SHLOCK − atomically obtain a shared lock

    • os.O_EXLOCK − atomically obtain an exclusive lock

    • os.O_DIRECT − eliminate or reduce cache effects

    • os.O_FSYNC − synchronous writes

    • os.O_NOFOLLOW − do not follow symlinks

  • mode − This work in similar way as it works for chmod() method.

  • dir_fd − This parameter indicates a file descriptor that refers to a directory.

Return Value

The Python os.open() method returns the file descriptor for the newly opened file.

Example

The following example shows the usage of open() method. Here, we are opening a file named "newFile.txt" by providing read-only access.

import os, sys

# Open a file
fd = os.open( "newFile.txt", os.O_RDONLY )

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("File contains the following string:", str)

# Close opened file
os.close( fd )
print ("File closed successfully!!")

The above code will open a file and read the content of that file −

File contains the following string: b'Tutorialspoint'
File closed successfully!!

Example

In the following example, we are opening a file with read and write access. If the specified file doesn't exist, the open() method will create a file with the same name.

import os, sys

# Open a file
fd = os.open( "newFile.txt", os.O_RDWR|os.O_CREAT )

# Write one string
os.write(fd, b"This is tutorialspoint")

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("File contains the following string:")
print(str)

# Close opened file
os.close( fd )
print ("File closed successfully!!")

On executing the above code, it will print the following result −

File contains the following string:
b'This is tutorialspoint'
File closed successfully!!
python_files_io.htm
Advertisements