Python | os.open() method

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 is used to open a specified file path and set various flags according to the specified flags and its mode according to specified mode.
This method returns a file descriptor for newly open file. The returned file descriptor is non-inheritable.

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



Parameters:
Path: A path-like object representing the file system path. This is the file path to be opened.
A path-like object is a string or bytes object which represents a path.
flags: This parameter specify the flags to be set for newly opened file.
mode (optional): A numeric value representing the mode of the newly opened file. The default value of this parameter is 0o777 (octal).
dir_fd (optional): A file descriptor referring to a directory.

Return Type: This method returns a file descriptor for newly opened file.

Code: Use of os.open() method to open a file path

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to explain os.open() method 
  
# 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
  
  
# Open the specified file path
# using os.open() method
# and get the file descriptor for 
# opened file path
fd = os.open(path, flags, mode)
  
print("File path opened successfully.")
  
  
# Write a string to the file
# using file descriptor
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(fd))
print("\nString read from the file descriptor:")
print(str.decode())
  
# Close the file descriptor
os.close(fd)
print("\nFile descriptor closed successfully.")

chevron_right


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.

Reference: https://docs.python.org/3/library/os.html#os.open



My Personal Notes arrow_drop_up

self motivated and passionate programmer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.