Python open()

file: specifies the file path object. Usually, a str or bytes object representing the file path. This is a mandatory argument.

mode: specifies the file opening mode. There are different modes to open a file.

r: opens file in read-only mode.

w: opens the file in write mode, the file is truncated.

x: open for exclusive creation, failing if the file already exists

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)

File opened in binary mode return content of file as bytes without any decoding. Whereas files opened in text mode contents are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding.

buffering: optional integer specifying the buffering policy. If passed as 0, buffering is turned off. This is allowed only when files are opened in binary mode. If passed as 1, line buffering is used and it’s allowed only in text mode. If passed greater than 1, then bytes of a fixed-size chunk buffer of specified size is used.

encoding: name of the encoding used to decode or encode the file. It should be used only in text mode.

errors: an optional string that specifies how encoding and decoding errors are to be handled, this cannot be used in binary mode. Some of the standard values are strict, ignore, replace etc.

newline: this parameter controls how universal newlines mode works (it only applies to text mode). It can be None, ”, ‘\n’, ‘\r’, and ‘\r\n’.

opener: A custom opener can be used by passing a callable as opener.

Most of the time, we use only file and mode parameters to open a file and perform necessary actions on it.

When a file is opened in text mode, TextIOWrapper instance is returned. When the file is opened in binary mode, BufferedRandom instance is returned.

Popular Categories

Newsletter for You

Don't miss out!

Subscribe To Newsletter

We promise not to spam you. Unsubscribe at any time.

Invalid email address

Thanks for subscribing!

JournalDev is one of the most popular websites for Java, Python, Android, and related technical articles. Our tutorials are regularly updated, error-free, and complete. Every month millions of developers like you visit JournalDev to read our tutorials.

JournalDev was founded by Pankaj Kumar in 2010 to share his experience and learnings with the whole world. He loves Open source technologies and writing on JournalDev has become his passion.