Python open() Example | File open() Function In Python

Python open() is an inbuilt function that opens the file and returns it as a file object. It is used in the file handling process. Python open() function returns the file  object which can be used to read, write, and modify the file. If a file is not found, then it raises the FileNotFoundError  exception.

Syntax:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Parameters:

  • file: The path name of the file to be opened or an integer file descriptor of the file to be wrapped.
  • mode: (Optional) An access mode while opening a file. Default mode is 'r' for reading. See all the access modes.
  • buffering: (Optional) Used for setting buffering policy. Defaults to -1. Pass 0 if specified mode is binary 'b',
  • encoding: (Optional) The encoding format to encode or decode the file.
  • errors: (Optional) String specifying how to handle encoding/decoding errors.
  • newline: (Optional) Conrols how newlines mode works. It can be None, '', '\n', '\r', and '\r\n'.
  • Closefd: (Optional) If a filename is given, it must be True. If False, the file descriptor will be kept open when the file is close
  • Opener: (Optional) A custom callable file opener.

Return type:

  • Returns a file object.

Python open() Function Example

Example 1:

# opens test.text file of the current directory
f = open("test.txt")

# specifying the full path
f = open("C:/Python33/README.txt")

Since the mode is omitted, the file is opened in 'r' mode; opens for reading.

Example 2:

# file opens for read  
f = open("path_to_file", mode='r')  
# file opens for write   
f = open("path_to_file", mode = 'w')  
# file opens for writing to the end   
f = open("path_to_file", mode = 'a')  

Output:

f = open("path_to_file", mode = 'r', encoding='utf-8')

In the above example, we specify different modes('r', 'w', 'a') for opening a file.

#python #python open

Python open() Example | File open() Function In Python
1.40 GEEK