This file()
function opens a file returning a file object.
Syntax
file(name, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Here,
- name: Optional. Full file path.
- mode: Optional. Possible values:
- ‘r’ open for reading (default)
- ‘w’ open for writing, truncating the file first
- ‘a’ open for writing, appending to the end of the file if it exists
- ‘b’ binary mode
- ‘t’ text mode (default)
- ‘+’ open a disk file for updating (reading and writing)
- ‘U’ universal newlines mode (for backward compatibility; should not be used in new code)
- buffering: Optional. setting buffering policy.
- encoding: Optional. the encoding format
- errors: Optional. a string specifying how to handle encoding/decoding errors
- newline: Optional. how newlines mode works (available values:
None
, ' '
, '\\n'
, 'r'
, and '\\r\\n'
- closefd: Optional. must be
True
(default); if given otherwise, an exception will be raised
- opener: Optional. a custom opener; must return an open file descriptor.
Examples
>>> f = open("test.txt")
>>> f = open("/home/cloudyfox/Downloads/test.txt")
>>> # In reading mode
>>> f = open("path_to_file", mode='r')
>>> # In writing mode
>>> f = open("path_to_file", mode = 'w')
>>> # opens for writing to the end
>>> f = open("path_to_file", mode = 'a')
>>> f = open("path_to_file", mode = 'r', encoding='utf-8')