Read and write – with statement

Another way in which you can read and write files is by using the with statement. The main benefit of using this statement it that any opened files will be closed automatically after you are done, so you don’t need to call the close() method manually.

To open a file using the with statement, the following code is used:

with open('FILENAME') as FILE_OBJECT:
    statements

For example, the following code will open new_file.txt and store the object in the file variable. We will the create a variable called text to store the text inside the file:

with open('new_file.txt') as file:
   text = file.read()

We can print the contents of the file:

print(text)

The output:

Have a nice day!
You too!

We can also use the with statement to write text to a file. We need to specify that we want to write to a file by calling the open() method with the w argument, and then use the write() method to write the content to the file:

with open('new_file.txt','w') as file:
    file.write('Hello World!')
The code above will overwrite any content found in new_file.txt. Just like with the open function used above, you can use arguments a and r+ to append text or open the file for read and write.
Geek University 2022