Python | os.open() method (original) (raw)

Last Updated : 11 Jul, 2025

**OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality.

****os.open()**method in Python opens a specified file path. This method returns a **file **descriptor for a newly opened file. The returned file descriptor is **non-inheritable.

os.open method is also used to set various flags according to the specified flags and file's mode according to the specified mode.

**Syntax:

**os.open(path, flags, mode = 0o777, *, dir_fd = None)

**Parameters:

**Return Type:

This method returns a file descriptor for a newly opened file.

List of flags that you can set on the new file:

**List of Flags
**Flag **Description
os.O_RDONLY Opens the file in read-only mode.
os.O_WRONLY Opens the file in write-only mode.
os.O_RDWR Opens the file in read and write mode.
os.O_NONBLOCK Opens the file in non-blocking mode.
os.O_APPEND Opens the file and places the cursor at the end of the contents.
os.O_CREAT Creates a file if it doesn’t exist.
os.O_TRUNC Truncates a file size to 0.
os.O_EXCL Shows an error while creating a file that already exists.
os.O_SHLOCK Obtains a shared lock for a file atomically.
os.O_EXLOCK Obtains an exclusive lock for a file atomically.
os.O_DIRECT Removes or reduces cache effects in a file.
os.O_FSYNC Writes file synchronously.
os.O_NOFOLLOW Sets the file that doesn’t follow a symlink.

How to use the os.open() method

We will use the **os.open() method to open a file path. Look at the code below to understand it better:

**Code:

Python3`

importing os module

import os

File path to be opened

path = './file9.txt'

Mode to be set

mode = 0o666

flags

flags = os.O_RDWR | os.O_CREAT fd = os.open(path, flags, mode) print("File path opened successfully.") str = "GeeksforGeeks: A computer science portal for geeks." os.write(fd, str.encode()) print("String written to the file descriptor.")

Now read the file from beginning

os.lseek(fd, 0, 0) str = os.read(fd, os.path.getsize(path)) print("\nString read from the file descriptor:") print(str.decode())

Close the file descriptor

os.close(fd) print("\nFile descriptor closed successfully.")

`

Output

File path opened successfully. String written to the file descriptor.

String read from file descriptor: GeeksforGeeks: A computer science portal for geeks.

File descriptor closed successfully.

In this tutorial, we have covered the os.open() method of the OS module to open a file. It is a very easy and straightforward way of opening files in Python.

We have explained how to use os.open() method with a sample Python program. This easy and simple tutorial will help you implement the os.open() method in your codes.