This guide covers Opening A File In Python 3.9 and explains the different ways in which you can open a file in Python 3.9. This is likely to come useful a couple of times in the future, feel free to use/copy paste the code for your own purposes as you see fit.

file = open("filename.txt")

The most basic example shown above, opening a file in read-only text (rt) mode.

Method Signature Open In Python

You open a file in Python with the open function. There is nothing to import in Python 3.9. The method has the following signature:

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):

How To Specify File Path When Opening A File In Python?

It has 6 parameters, the first one is the path of the file that you want to open. This can be existing file if you are planning to read from a file or it can be new file that you plan to create by writing.

How To Specify The Mode When Opening A File In Python?

The second parameter refers to the different modes in which you can open the file. For example you can open a file in write mode with the following setting:

file = open("file.txt","w")

Find below a table to check the different modes available to open files in python that you can also combine together. For example the default mode is ‘rt’.

'r'       open for reading (default)
'w'       open for writing, truncating the file first
'x'       create a new file and open it for writing
'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 newline mode (deprecated)

Buffering When Opening A File In Python

The third parameter is buffering. By default buffering behaviour will depend on whether you are using binary or text mode to access the file. Files are read in fixed size chunks (buffering > 1) that you can specify and interactive text files are read by line (buffering=1). You can disable buffering by setting it to 0.

For example if you try to read a text file with buffering=0 you will get a ValueError: can’t have unbuffered text I/O error.

How To Specify Encoding When Opening A File In Python?

The fourth parameter encoding. This should only be used in text mode. You can find them at

An example using encoding is as follows:

file = open("filename.txt","w", encoding="UTF8")

The fifth parameter is errors, related to the encoding. Errors is an optional string that specifies how encoding errors are to be handled—this argument should not be used in binary mode. Pass ‘strict’ to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass ‘ignore’ to ignore errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register or run ‘help(codecs.Codec)’
for a list of the permitted encoding error strings.

Newline Considerations When Opening A File In Python

The sixth parameter is newline and this one also only works in text mode. The default mode is called Universal mode. Upon input, Lines ending with ‘\n’, ‘\r’, or ‘\r\n’ are translated into ‘\n’ before being returned to the caller.

What Does closefd Do When Opening A File In Python?

The final parameter clode. The important point is firstly that you can use a string or bytearray as a file for both reading and writing. Closefd has to be True for files and can be False when using the above mentioned types. If you try to set closefd as false for a file you will get the following error:

ValueError: Cannot use closefd=False with file name

That was it, let us know any specific articles on Python that you would like to see! If you want to check how to log in JSON with Python check this article: Python logging json formatter