How to read from file in python

File handling and management is one of the python's functions that made the programming language an interesting and indispensable for the programmers. Ability to open, read, and write to a file gives python more acceptability in the programmining world. In this atticle, we will delve into how python's handling files in terms of opening, reading, and writing task is possible. We will see how individual task is being done.

Reading From Files

Before a file can be read in python, such file must first be opened. User can then commence any task on such a file. Follow the syntax code below to open a file for reading.
file object = open(file_name, access_mode)

file = open('filename.txt', 'r')
Explanation:
Python uses open() function to open a file. This function takes two arguments, which is filename (including the path) and mode of opening the file. The command above has two segments, with equal (=) sign being in the middle, thus file = open('filename.txt', 'r'). The first part which is "file" is a variable name (you can call it anything). Equal (=) sign in the middle tells python to use "open()" function in the right to open "filename.txt" in reading mode, denoted by "r" and store it in the "file" variable name.

Let us use a real txt file name to describe this analogy. Open a notepad and create a file, name this file days.txt, save the file to your working folder (example d:\days.txt) so that it can be easily located. Now let us open days.txt and write data into it

f = open("d:\days.txt", "r") ## the file is located in d:\directory

Brilliant! days.txt has been opened in read mode and stored in "f" variable.
Now let us see the content of this file, that brings inn another command that will display the content of the file. To do that use the following command:

f = open("d:\days.txt", "r")

content = f.read()
print(content)

Explanation:
There are 3 line of codes in the above program, line 1 opens days.txt in read mode and store it in "f" variable line 2 created a variable "content", read the content of "f", which is the content of "days.txt file" and put put it in the "content" variable. The last line, which is line 3, tells python to display what is inside the "content" variable. See the output below:

Seven days make a week!

This document was last modified: