Reading a file
Once the file is opened in read mode, it will be necessary to read its contents. If the file is text-based, you can use the read () method.
For the example in this section, create a text file and insert the following text in it. Then save it as prova.txt.
Questo e’ il contenuto
del file di testo.
Then to read the content and print it on the terminal, write the following code.
file = open("prova.txt","r") content = file.read() print(content) file.close()
by executing the code you will get the following:
>>> Questo e' il contenuto del file di testo.
As you saw, the entire multi-line content was read and reported to output. But we often want to read only one particular line of this file. In this case the readline () method reads one line at a time. The first call reads the first line, the second line the second line, and so on.
file = open("prova.txt","r") content = file.readline() print(content) file.close()
By executing only the first line will be read.
>>> Questo e' il contenuto
This way we have more control of reading the file.
And if we wanted to scan all the lines of a text file, and process one at a time, iteratively we can use a for loop.
file = open("prova.txt","r") for line in file: print(line) file.close()
Finally, it is interesting to know that it is possible to create a list with elements for the individual lines of a text file. The readlines () method is used (not to be confused with readline ()).
file = open("prova.txt","r") content = file.readlines() print(content) file.close()
By executing, you can see how a list of strings is content
>>> ["Questo e' il contenuto\n", 'del file di testo.\n']