OPEN/CLOSE FILES IN PYTHON

GOCOURSE



Open

If we want to process a file for either read or write operation, the file must be opened first. The opening of a file is done with the help of open() method.

Keyword:

    Open()

Syntax:

file_object=open (file_name[,'mode'] [, buffering])

The open() method returns a file object with allocated buffer size when the specified file is successfully opened on the specified mode. The file object refers the allocated buffer for file processing operations.

Close

The close method used to clear the allocated buffer and unwritten information and release the file object. No more read and write operation can be done on the file object after that .

Keyword:

  Close()

Syntax:

file_object.close()

The python produces an error message, if we try to close an unopened or unassigned file object.

Program:


  # Open a file in read mode
  file = open('file.txt', 'r')

  # Read the content of the file
  content = file.read()

  # Print the content of the file
  print(content)

  # Close the file
  file.close()




More topic in Python

Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send