This was a very challegnig thing i’ve got to get through in  the semester.

To learn how to open and read files i had to read a lot of times the same thing of the “How to think like a computer scientist”

There are special words to do this how ever the esscentials does not need you to import any module which is good for us.

First of all we have to tell python we want to open a file, to do this we must type set a variable and set the open to it like this:

variable = open(“name of the file.txt”, “r”)

It is very important that we put our paraeters in this case within quot marks, as you see up you have to type an ‘r’ after the name of the text which indicates that is reading.

Now we have it open we have to read it.

To read the text we can choose between read line by line orto read all of them.

1 line at a time: variable = previous_variable.readline()

all of them: variable = previous_variable.readlines()

From here you just haveto get creative and do the stuff you want. And just dont remember that always at the end you must close your text with:

variable.close

An example:

archivo = open(‘bananas.txt’, ‘r’)

one = archivo.readline()

print (one)

close.archivo

 

Hope you enjoy it!

 

 

 

CC BY 4.0 Open and read files by fersabal is licensed under a Creative Commons Attribution 4.0 International License.