Reading and writing files using python
Python can be used to open, read and write files. Let's take an example of a simple csv file. csv stands for comma separated values. csv files are basically text files with lines of text wherein each element in a line is separated by a comma. Below is an example of a csv file open in notepad.
We will see here two ways to open this file in python.
- open()
- with
open()
While using the open() function you have to first define a variable for it. The open() function does not close the file automatically so you have to use a close() function as well. Following is how you use it.
f1 = open('animal_habitats.csv', 'r')
data = f1.readlines()
f1.close()
The argument "r" means that we are opening the file in read mode. Once the file is opened, the readlines() function is used to read all line in the file and store it in a variable.
For opening the file in write mode, we have to use "w" as the argument. The "w" argument creates an empty file. For writing information in preexisting file, we need to open the file in append mode by using "a" as the argument.
To browse through the data (for example printing the data) we can simply use a for loop.
for line in data: print(line)
with
With function uses the open() function. However, it also closes the file automatically. Therefore we do not need to use a close() function.
with open("animal_habitats.csv", 'r') as f: s = f.read()
Note that we have to use a colon (:) at the end of "with open()" statement. The f.read() function above stores all the data in a single string, while the readlines() function stores each line as a string and the whole file is in the form of a list of the lines.
Writing files:
Let's now see an example of writing file. First we have to open the file in write mode. Then we need to write the data in string format. The new line character "\n" needs to be written explicitly.
f = open('output.txt', 'w')
f.write("Mary had a little lamp, little lamp, little lamp! \n")
f.write("Its fleece was white as snow.\n")
f.write("And everywhere that Mary went, Mary went, Mary went!\n")
f.write("The lamb was sure to go.")
f.close()
The output file will look like this when opened in notepad.