![Python Lessons - 4.9 Handling files](https://www.meccanismocomplesso.org/wp-content/uploads/2018/04/Python-Lessons-4.9-Handling-files--1024x196.jpg)
Handling files
In the previous sections you have seen how to read and write data within a file, but there are some precautions to follow. You have seen that it is important to always close the file we are working on while running the program.
But if something goes wrong? If you generate an unhandled exception, the program execution stops and the file remains open?
To overcome this problem we have seen in the first sections of this part of the course what the exceptions are and how to manage them. So it is clear that to work with files you need to use a try-except construct.
So the cleanest and safest way to work with files is as follows:
try:
file = open("prova.txt", "a")
file.write("Questo è il nuovo testo\n")
finally:
file.close()
In this way, however, go, we will be sure that the file is closed (a good example to understand the utility of finally).
An alternative, less used way of working with files is by using the with clause. This command allows you to create a temporary variable and refer to it within the block to execute all the methods. At the end of the with construct, the variable is destroyed, even if an exception occurs.
with variabile as f:
blocco with
In the case of files then this construct could be very useful:
with open("prova.txt","w") as f:
file.write("Questo è il nuovo testo\n")