Python tutorial reading and writing files

In this tutorial we will deal with the reading and writing to files in python. First lets talk about creating the actual file and the various options you have.

When dealing with files you may have various types of modes some of these modes are as follows.

  • w for write if an existing file exists it will be overwritten.
  • just read the file and not do anything else.
  • r+ open the file for reading and writing.
  • append to an existing file.

Reading a file in python

First of all we need to open our file by doing the following:

f = open('test.txt', 'r')

So first of all create a test.txt file so that you have something to read. For our test.txt file we added the following information.

Example of a test.txt for reading files in python
Example of a test.txt for reading files in python

Once you have your file open up the python terminal and type in the code we showed in the example above. You should see something similar to the following now.

Example of the read output of our python script
Example of the read output of our python script

Alternatively you can use the readline function to read a line at a time. Whereas the read function you can pass a read size and read a certain number of characters.

At some point you would want to read multiple lines from your file so what you will do is put your reading in the loop. Like below:

for line in f:

Writing to files in python

Let’s get to writing information to a file. To do this you can do the following.

f = open('test2.txt','w')
f.write('my name is sarah\n')

You will see something similar to this.

Writing data to a file in python example
Writing data to a file in python example

Try and experiment with some of the other file modes such as w,a,r,r+ and see how they work. It’s always better to try and experience and experiment on your own after going through a tutorial for maximum understanding.

Comments 2

  • Although I’m complete noob, I did learn that best way to handle files is:

    with open(“my_file.txt”) as f:

    Since you don’t have to worry about forgetting to close the file.
    Tutorials in 2017 should be teaching best practice.

    • hi alamanjani, even though this is what you consider best practice. Let me put the following point to you. In terms of coding security on larger projects with a number of developers. You would much rather want stricter parameters in your opens to avoid things such as race conditions, file overwriting by multiple processes and more. Control the end of the day is important. I do however agree that your method is better suited for a very simple application as in this tutorial. However in bigger projects I’d advise to be very specific about the file operations you are taking.

Leave a Reply

Your email address will not be published. Required fields are marked *