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.
- r just read the file and not do anything else.
- r+ open the file for reading and writing.
- a 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') f.read()
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.
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.
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: print(line,end='')
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.
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.