Wednesday, August 5, 2020

Python os.fdopen() Method with example



Hello dear readers! Welcome back to another section of my tutorial on Python. In this tutorial guide, we are going to be studying about the Os fdopen() method.

The Python's os fdopen() method returns an open file object that is connected to the file descriptor fd. Then you can now perform all the defined functions on file object.

Syntax

Below is the syntax for Python Os fdopen() method -

os.fdopen(fd,  [ ,  mode[,  bufsize] ] );


Parameter Details

  • fd - It is the file descriptor for which a file object is to be returned.
  • mode - This is an optional argument, and it is a string indicating how the file is to be opened. The most often used values of mode are 'r' for reading, 'w' for writing and 'a' for appending.
  • bufsize - This is an optional argument, and it is used for specifying the file's desired buffer size; 0 simply means unbuffered, then 1 means line buffered, and any other positive value means use a buffer of that size.

Return Value

This method returns an open file object which is connected to the file descriptor.

Example

The following below is a simple example -

#!/usr/bin/python

import os, sys

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

# Now get a file object for the above file.
fo = os.fdopen(fd, "w+")

# Tell the current position
print "Current I/O pointer position :%d" % fo.tell()

# Write one string
fo.write( "Python is a great language.\nYeah its great!!\n");

# Now read this file from the beginning.
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print "Read String is : ", str

# Tell the current position
print "Current I/O pointer position :%d" % fo.tell()

# Close opened file
fo.close()

print "Closed the file successfully!!"

Output
When the above code is executed, it will produce the following result -

Current I/O pointer position :0
Read String is :  This is testPython is a great language.
Yeah its great!!

Current I/O pointer position :45
Closed the file successfully!!


Alright guys! This is where we are rounding up for this tutorial post. In my next tutorial, we are going to be discussing about the Python OS fpathconf() Method.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.