Mastery 30. Reading and Writing of files in python

In this post we will se how to use read() and write() methods in order to read and write files.

First of all we have to create the file in which we are going to write the text, for that, we have to create an object to which we are going to assign the “open” function.

The open function has two parameters, the first one is the name of the file you are creating and the second one is to check if it would be destinated to write or read. After the file is created we can write in it by first typing the name of the object we created, followed by a dot and the “write” function which has as a parameter the actual text you want to write in this new file, also is important to mark that the end line character is given by “/n”. At the end we have to close our object in order to save memory; this can be done by typing the name of our object followed by dot and the function close() without any parameter. Lets see the next example:

In this case we created an object “fw” with which we created a text file called “example”, in which we wrote some stuff. By running this code from our terminal the next file is created:

  And if we open it we can se that what we wrote in our code was actually written in this new file.

 

Now that we know how to use the write() method to write in a file, lets se how to use the read() method to read it.

As in the write() method we hace to cretae a new object to which we can assign the open function, but in this case, we are going to use the second parameter to read the file.

Using the read() method we have to create a new cariable to which we can assign the object, and then we can do whatever we want with this new variable, such as print it. Also, as in the write() method, we have to close our object in order to save momory from out computer. Lets see the next example:

In this example we are creating an ‘fr’ object with a first parameter ‘example.txt’ which is the file we want to read, and a second parameter ‘r’ indicating that we are going to read it.

the text variable is getting the actual text from the file, and then by print it we can see what was in it. By running this code from our terminal we get the following:

Which as we can see, is exactly what we had written at the beginning by using the wite() method.

CC BY 4.0 Mastery 30. Reading and Writing of files in python by Manuel Madrigal is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.