Read files with python

 How to read files with python

In this blog, we will show how to read files with python. We will do it first in an interactive way, then via a .py script.

First go to python

Create a variable with the file path of the text file you want to read

Open the text tile with the open function,  we are opening in 'r' means in read mode. Assign the opening to open_file_r. The open_file_r is a class that will have methods attributes and methods such as (read(), close())

Then execute the read method, and assign the output to a variable called file_content
By reading the file with the read() method, the output will be a string. 
So the file_content variable is a string containing the content of the file. See screenshot below


Then we call the method close to close the file




Below is another way to read the file instead of reading the entire file to one string, we are reading the file to a list. each line in the file is parsed to an element in the list. See below



If you would like to know more about services in scripting and network automation, click to visit our website http://http-cloud.com/it-services
We hope this was helpfull and we would like to thank you for reading









Comments