Skip to main content

Python Basics Read Text File and placed into variable

Python code below is a simple and basic code, that will open a text file in read only mode.

Code below has been tested using Python3.

It just demonstrates using a “print” statement to show the logic; how to open a file in read only mode and place the line that was read to a variable.

The logic can be used on advance methods, such as replacing the line with IP Address and supplying a shutdown command to the IP Address.

Here’s the code:

#Open the file as Read Only

with open('mysampledata.txt','r') as file_objHandler:

#'mysampledata.txt' <--file name of the text file to be read

#'r' <-- tell Python to open file as read only

 

 #Read all lines in the file. 

 TxtLines = file_objHandler.readlines()

 

 line_counter = 0

 for Oneline in TxtLines:   

    #print(Oneline.strip())

    line_counter += 1

    print(line_counter, "<-- Line# / This is the data on the text file -->", Oneline)

    #line_counter <-- is a variable that will get increment

    #Oneline <-- is a variable that holds a single line that was read from the textfile


Sample Output:




Cheers! Take care. Till next Time.

Stay safe! and Keep things up! 

Do ASAP, Always Say A Prayer...

Practice O.T.G. = Obedience TGod

================================

Free Android Apps:

Click  links below to find out more:

Free Android Apps:

Click  links below to find out more:

Excel Keyboard guide:

https://play.google.com/store/apps/details?id=chrisjoms.myexcelapplicationguide

Heaven's Dew Fall  Prayer app for Android :

https://play.google.com/store/apps/details?id=soulrefresh.beautiful.prayer

Catholic Rosary Guide  for Android:

Pray the Rosary every day, countless blessings will be showered upon your life if you recite the Rosary faithfully. 

https://play.google.com/store/apps/details?id=com.myrosaryapp

Divine Mercy Chaplet Guide (A Powerful prayer) BFF = Be Filled Faith:

https://play.google.com/store/apps/details?id=com.dmercyapp   

Comments