Reading and writing of files in Python

For reading and writing of files in python, the first thing you need to do is to get a file object, using the “open” function.

The open function has two parameter, the first one is the name of the file that we are creating and the other parameter is going to check if you are going to read(r) or write(w) the file. Now to write inside the file you need to write the name of the object we just created followed by a dot with the word “write” adn you open parenthesis where you are going to write the text.It is important to point out that the end line is given by “/n”. To save it we just have to close our object.

this is the syntax: file = open(“newfile.txt”, “w”)

                                           file.write(“hello worldn”)

                                           file.write(“this is another linen”)

                                           file.close() 

the object name is file and the text file is example.

Now we know how to use write(), I can explain read().

read() is used for reading the text file. The syntax is very simple like with the write() method, just where we wrote “w” now we have to write “r”.

this is the syntax of this:

                                              file = open(‘newfile.txt’, ‘r’)

                                              print file.read()

                                              file.close()

In this example it shows us the two parameters, the first one tells us what the text file is going to open and the second parameter tells us what is going to do. In this case “r” means that is going to read. Print means that when you are in the terminal, it will print the text that is in the file. In this case it will print:

                                              hello world 
                                              this is another line

We can also specify how many characters the string should return, by using
file.read(n), where “n” determines the number of characters.

This reads the first 5 characters of data and returns it as a string.

In this case, it will print : hello

I learned all this stuff on this web page, you may want to check it out:  http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

30

1014

CC BY 4.0 Reading and writing of files in Python by Jorge Padilla is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.