In this lesson, you will learn how to do the most basic operations — opening and closing of files.
How to open files
In Python, we open a file using the open
function, which requires the file path and the mode as parameters. The path is straightforward. We use the mode to specify how we want to use the file:
- To write or read
- To work with text or binary data
- To clear the file before writing to it
Now, we will work with files in two modes — for reading and writing text. To read something from a file, we first need to create it and write something into it. Let's start with that. We will open a file for writing:
f = open('foo.txt', 'w')
f # <_io.TextIOWrapper name='foo.txt' mode='w' encoding='UTF-8'>
The variable f
now refers to a file object. Don't be alarmed by the type name. For now, you can pay attention only to the parameters:
name
specified when callingopen
mode
specified when callingopen
encoding
set to the default UTF-8, which is what you will mostly need
So, we have opened the file. Let us try to close it:
…
f.close()
f.closed # True
Here, closed
is an attribute of the f
object. Attributes are variables within the associated object.
How to close files
Python is a language with automatic memory management. Knowing this, you can guess that the execution environment will close the file when we delete the last reference to the file object. It's easy.
In simple cases, we do not have to close files manually because scripts usually run briefly and don't open many files. Therefore, closing files upon script completion is generally acceptable. However, longer programs that run for extended periods may need to ensure that files are closed on time, preferably immediately after you read or write the required data to or from them.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.